Sub topic 6
Fixing N+1 with JOIN FETCH
This chapter assumes you know basic JPA mapping (@Entity, @OneToMany, @ManyToOne), Spring Data JPA repositories, and SQL joins. It uses the Author and Book model from earlier chapters. You have seen how authorSummaries() issues one query for the authors and then one query per author to load getBooks(). Here you fix that with JOIN FETCH.
What JOIN FETCH does
JOIN FETCH is a JPQL keyword that tells Hibernate to load an association in the same SQL statement as the root entity. Hibernate adds a SQL join, selects the columns of both tables, and fills the lazy association for you. When your code later calls author.getBooks(), the collection is already initialized and no extra query runs.
A plain join in JPQL only affects filtering and ordering. It does not load the association. join fetch changes what is loaded.
| JPQL | Effect on the association |
|---|---|
| `select a from Author a join a.books b where b.title like ...` | Joins for filtering. `a.books` stays uninitialized. |
| `select a from Author a join fetch a.books` | Joins and initializes `a.books` for every returned author. |
The fix in a repository
Add a query method to the repository:
public interface AuthorRepository extends JpaRepository<Author, Long> {
@Query("select distinct a from Author a join fetch a.books")
List<Author> findAllWithBooks();
}Then use it in the service instead of findAll():
@Service
public class AuthorService {
private final AuthorRepository authorRepository;
public AuthorService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Transactional(readOnly = true)
public List<String> authorSummaries() {
return authorRepository.findAllWithBooks().stream()
.map(a -> a.getName() + ": " + a.getBooks().size())
.toList();
}
}The SQL Hibernate generates looks roughly like this:
select a.id, a.name, b.id, b.title, b.author_id
from author a
join book b on b.author_id = a.idInstead of 1 + N statements, you get one. With 100 authors, that is 1 statement instead of 101.
Why the result is wider
A SQL join returns one row per author-book pair. An author with three books appears in three rows. Hibernate reads those rows and builds one Author object with three Book objects in its collection.
author_id | author_name | book_id | book_title
1 | Ada | 10 | Notes A
1 | Ada | 11 | Notes B
2 | Grace | 12 | CompilersThe database transfers the author columns once per book. For wide parent rows and large collections, this duplication increases network traffic and memory use. This is the main cost of a collection fetch join.
The role of distinct
Before Hibernate 6, a collection fetch join returned the parent entity once per joined row. A query for authors with three books returned the same Author instance three times, so distinct was needed to remove duplicates. In Hibernate 6 and later, which Spring Boot 3 uses, Hibernate deduplicates parent entities in the result list automatically. Writing distinct is harmless. It makes the intent clear and keeps the query correct if you run it on an older version.
Note that distinct in JPQL is also passed to SQL in many cases, so the database may do extra work to deduplicate rows. In Hibernate 6 the SQL distinct is not required for in-memory deduplication. Check your logged SQL if the query is hot.
Inner join versus left join fetch
join fetch is an inner join. Authors with no books do not appear in the result. This is a common bug: the N+1 problem disappears, but some authors silently go missing.
If you want every author, use left join fetch:
@Query("select distinct a from Author a left join fetch a.books")
List<Author> findAllWithBooksIncludingEmpty();For authors without books, getBooks() returns an empty, initialized collection.
Fetching with filters
You can add where conditions to a fetch join, but be careful about what they mean. Consider:
@Query("""
select distinct a from Author a
join fetch a.books b
where b.title like :prefix
""")
List<Author> findByBookTitlePrefix(@Param("prefix") String prefix);This returns authors who have at least one matching book, and each author's books collection contains only the matching books. The collection in memory no longer represents the full database state. If the persistence context later flushes or you pass this entity around, other code may assume it holds all books.
Hibernate discourages filtering on a fetched alias for this reason. If you need authors who have a matching book but want all their books loaded, filter with a subquery or exists:
@Query("""
select distinct a from Author a
join fetch a.books
where exists (
select 1 from Book b2
where b2.author = a and b2.title like :prefix
)
""")
List<Author> findWithAllBooksWhereAnyTitleMatches(@Param("prefix") String prefix);Fetching the many-to-one side
JOIN FETCH also solves N+1 in the other direction. If you list books and read book.getAuthor().getName(), the lazy @ManyToOne triggers one query per distinct author. Fix it with:
@Query("select b from Book b join fetch b.author")
List<Book> findAllWithAuthor();A to-one fetch join does not multiply rows, because each book has one author. This is the cheapest kind of fetch join, and you should use it freely when you know you need the association.
Common mistakes
- Using
join fetchand then not using the association. You pay for the wider result set and gain nothing. Fetch only what the calling code reads. - Forgetting the inner join effect. Parents without children vanish.
- Fetching two collections at once. A query such as
join fetch a.books join fetch a.awardscan throwMultipleBagFetchExceptionwhen both areListcollections without an order column. It also produces a Cartesian product of rows. A later chapter covers this. - Combining a collection fetch with pagination. Passing a
Pageableto a collection fetch join makes Hibernate apply the limit in memory after loading all rows, and it logs a warning (HHH90003004). A later chapter shows the two-step approach. - Writing
join fetchwith an alias and reusing it inwhere. This changes the contents of the loaded collection, as shown above. - Putting
join fetchin a query used for counting. A count query forPageresults must not contain a fetch. Spring Data derives a count query from your JPQL, and fetch joins can break it. Provide a separatecountQuerywhen needed.
Verifying the fix
Turn on the statistics settings from the earlier chapter and call authorSummaries() again. In the log you should see a single select with a join, and the prepared statement count should be 1.
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.generate_statistics=true
logging.level.org.hibernate.SQL=DEBUGIf you still see per-author selects, check that the service calls the new method and not findAll(). Also check that the association you read is the one you fetched. Fetching books does not initialize other lazy associations on Book, such as book.getPublisher().
Strengths and limits
| Aspect | JOIN FETCH |
|---|---|
| Number of statements | One |
| Control | Explicit per query, visible in the JPQL |
| Row duplication | Yes for collections, no for to-one |
| Pagination of collections | Not safe |
| Multiple collections | Problematic |
| Returns | Managed entities, so changes are tracked |
JOIN FETCH is the most direct fix when one query needs one collection and does not paginate. The next chapter shows @EntityGraph, which expresses the same fetch without editing the JPQL.
Exercise
A developer replaces findAll() with select a from Author a join fetch a.books. The query count drops to 1, but the author list now has fewer entries than before. What causes this, and how do you fix it?
Show answer
join fetch is an inner join, so authors with no books produce no joined rows and are left out. Change the query to select distinct a from Author a left join fetch a.books so that authors without books are returned with an empty collection.
Exercise
You add where b.title like :prefix to a query that uses join fetch a.books b. What does each returned author's getBooks() contain, and why can that be a problem?
Show answer
It contains only the books whose title matches the prefix, because the where clause filters the joined rows that Hibernate uses to fill the collection. Other code may treat the collection as the author's complete list of books. To load all books for authors that have a match, filter with an exists subquery instead.