Fetchingmedium3-5 years

An endpoint lists 500 authors with their books and takes eleven seconds; the code has no loop over queries anywhere. A teammate fixes it with `select a from Author a join fetch a.books`, and it is fast — but two authors have vanished from the list. Explain both problems.

The first problem is N+1: one query loads the 500 authors, and then touching each author's lazy books collection fires one more query per author, 501 round trips in total. There is no loop over queries in the code because there is a loop over objects, and the queries are a side effect of it. The fetch join fixes that with one query, but join fetch is an inner join, so an author with no books has no row to join to and silently disappears from the result. The correct fix is left join fetch, or an entity graph (which Hibernate runs as a left outer join), so childless authors stay in the list.

The lesson behind it →