Sub topic 11
Choosing a strategy
This chapter assumes you know the N+1 problem, the persistence context, and the four fixes from the earlier chapters: JOIN FETCH, @EntityGraph, batch fetching, and DTO projections. Here you decide which fix to use for a given query.
Start with what the caller needs
Ask two questions before you change any query:
- Does the caller need entities, or only values to display?
- Does the query fetch a collection, a single-valued association, or nothing at all?
The first question matters most. If the code only reads data and never modifies it, a DTO projection is usually the best choice. It selects exactly the columns you need, creates no managed entities, and cannot trigger lazy loading.
Compare the options
| Strategy | Best for | Main cost |
|---|---|---|
| DTO projection | Read-only lists, reports, aggregates | You write a query and a type for each view |
| `JOIN FETCH` | One use case that always needs the association | The query is tied to that use case |
| `@EntityGraph` | The same, with the query left unchanged | Each graph is as specific as a `JOIN FETCH` |
| Batch fetching | Many call sites, unpredictable access | Still runs extra queries, about N/batch size |
| Two-step id query | Paged lists with a collection | Two queries, and you must restore the order |
JOIN FETCH and @EntityGraph give the same result. Use @EntityGraph when a derived or existing query is fine and you only want to add the fetch. Use JOIN FETCH when you are already writing JPQL.
Use batch fetching as a default, not a fix
Setting hibernate.default_batch_fetch_size costs nothing and applies everywhere. It turns 1 + N queries into 1 + N/50 for code you have not tuned yet. It does not remove the extra queries. For a hot path, a targeted JOIN FETCH or projection still wins, because it needs one statement.
Handle paging with collections
A collection fetch join combined with paging forces Hibernate to apply the limit in memory, after loading every row. Choose between two approaches:
- Page the ids in SQL, then fetch those authors with their books. This is the two-step approach from the pitfalls chapter.
- Skip the fetch join and rely on batch fetching. The page is limited in SQL, and the collections load in a few batched queries.
This service method uses the two-step approach and restores the page order:
@Transactional(readOnly = true)
public List<Author> authorsPage(int page, int size) {
Page<Long> ids = authorRepository.findAuthorIds(
PageRequest.of(page, size, Sort.by("id")));
Map<Long, Author> byId = authorRepository.findWithBooksByIdIn(ids.getContent())
.stream()
.collect(Collectors.toMap(Author::getId, Function.identity()));
return ids.getContent().stream().map(byId::get).toList();
}Avoid common mistakes
- Do not fix N+1 by switching the mapping to
FetchType.EAGER. Every query then loads the association, including queries that do not need it. - Do not fetch two
Listcollections in one query. Hibernate throwsMultipleBagFetchException, and using aSetonly hides a Cartesian product of rows. - Do not tune without measuring. Check the statement count with the statistics settings, then lock the result in with a query-count test.
Exercise
An endpoint returns page 3 (20 authors per page) with each author's books as entities that the caller will update. Which strategy do you choose, and why not a plain join fetch a.books with a Pageable?
Show answer
Use the two-step approach: page the author ids in SQL, then load those authors with join fetch on a.books, and reorder by the id list. Batch fetching on the collection is a valid alternative. A paged collection fetch join makes Hibernate load all matching rows and apply the limit in memory. A projection does not fit because the caller needs managed entities to update.