Sub topic 6
Fixing N+1 with JOIN FETCH
This chapter assumes you know basic JPA mapping, Spring Data JPA repositories, and SQL joins. It also assumes you have seen the Author and Book model and the N+1 pattern from the earlier chapters.
The problem we are fixing
authorSummaries() calls findAll() and then getBooks().size() for each author. That is one query for the authors plus one query per author for the books. With 100 authors you get 101 statements.
The cause is that the default findAll() query does not load the books. The lazy collection stays uninitialized until you touch it. To fix this, tell Hibernate to load the books in the same query.
What JOIN FETCH does
JOIN FETCH is a JPQL keyword. It adds a SQL join and also fills the association on the returned entities. A plain join only lets you filter or sort by the joined table. It does not initialize the collection.
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface AuthorRepository extends JpaRepository<Author, Long> {
@Query("select distinct a from Author a join fetch a.books")
List<Author> findAllWithBooks();
}Hibernate runs one SQL statement that joins author to book. Each author in the result has its books collection already populated, so getBooks().size() triggers no further query.
Using it in the service
Change the service to call the new method:
@Transactional(readOnly = true)
public List<String> authorSummaries() {
return authorRepository.findAllWithBooks().stream()
.map(a -> a.getName() + ": " + a.getBooks().size())
.toList();
}The SQL log now shows one select instead of 1 + N.
Why distinct
A join returns one row per book. An author with three books appears in three rows. Without distinct, older Hibernate versions (5 and earlier) return the same Author instance three times in the list. Hibernate 6, which Spring Boot 3 uses, removes these duplicates from entity results automatically. Keeping distinct is harmless and makes the intent clear.
Inner versus left join fetch
join fetch is an inner join. An author with no books is dropped from the result. If you want every author, including those with an empty collection, use left join fetch:
@Query("select distinct a from Author a left join fetch a.books")
List<Author> findAllWithBooksIncludingEmpty();Pick the join type from the result you need, not from habit. Using the inner form by mistake is a common source of "missing rows" bugs.
Limits to know about
- The fetch is fixed in the query text. Every caller of
findAllWithBooks()pays for the join, even if it only needs author names. - You cannot put an alias on the fetched association and filter on it without changing which books are loaded. A
whereon the fetched alias leaves the collection incomplete, which hides data. - Fetching a collection combined with
Pageablemakes Hibernate page in memory. A later chapter covers this and the fix. - Fetching two
Listcollections at once fails with aMultipleBagFetchException. This is also covered later.
Verify the result
Keep the properties from the detection chapter enabled:
spring.jpa.properties.hibernate.generate_statistics=true
logging.level.org.hibernate.SQL=DEBUGCall the service and count the logged select statements. You should see exactly one.
Exercise
Your endpoint must list every author, including authors who have written no books, with their book counts. You switch from findAll() to a query using "join fetch a.books", and authors without books disappear. What is the cause and the fix?
Show answer
join fetch is an inner join, so authors with no matching book rows are excluded. Change the query to "select distinct a from Author a left join fetch a.books", which keeps authors with empty collections.