Sub topic 11
Choosing a strategy
This chapter assumes you have read the earlier chapters on the author and book model, lazy loading, and the four fixes: JOIN FETCH, @EntityGraph, batch fetching, and DTO projections. It also assumes you know basic JPQL and Spring Data repositories. Here you learn how to pick one fix for a given query. You will not learn a new technique.
Why there is no single best fix
Each fix changes the SQL in a different way. JOIN FETCH and @EntityGraph load the parent and its children in one joined statement. Batch fetching keeps the lazy model but loads children for many parents per statement. A DTO projection skips entities entirely and reads only the columns you need.
Each approach costs something. A join repeats parent columns for every child row. Batch fetching still issues several statements. A projection gives you objects that are not managed, so you cannot modify them and save the changes. The right choice depends on three things: what the caller does with the result, how large the result is, and how the data is shaped.
Start with the question: read or write?
Ask first whether the code will change the entities it loads.
- If it only reads and shows data, prefer a DTO projection. It selects the least data and cannot trigger lazy loading by accident.
- If it modifies entities and relies on dirty checking, you need managed entities. Choose among
JOIN FETCH,@EntityGraph, and batch fetching.
Dirty checking is the mechanism where the persistence context compares each managed entity with its loaded state at flush time and writes the changes. It only works for entities, not for DTOs.
Decision flow
The diagram below summarizes the order of questions.
Treat the diagram as a starting point. Measure the statement count and the timing before you commit to a choice.
Comparing the options
| Strategy | Statements for N authors | Returns | Works with paging | Main risk |
|---|---|---|---|---|
| `JOIN FETCH` | 1 | Managed entities | Not for collections | In-memory paging, duplicated rows |
| `@EntityGraph` | 1 | Managed entities | Not for collections | Same as `JOIN FETCH`, plus a graph that is easy to overlook |
| Batch fetching | 1 + about N/50 | Managed entities | Yes | More than one statement, loads whole collections |
| DTO projection | 1 | Plain objects | Yes | No dirty checking, one query per use case |
The statement counts assume the batch size of 50 from the batch fetching chapter.
Choosing between JOIN FETCH and @EntityGraph
Both produce the same joined SQL. The choice is mostly about where you want the fetch decision to live.
Use JOIN FETCH when the query is written in JPQL and the fetch is part of what the query means. The join sits next to the where clause, so a reader sees the full statement in one place.
@Query("select distinct a from Author a join fetch a.books")
List<Author> findAllWithBooks();Use @EntityGraph when you want to keep a derived query method or a shared query and only add a fetch hint. It also lets you reuse one query with different graphs.
@EntityGraph(attributePaths = "books")
@Query("select a from Author a")
List<Author> findAllWithBooksUsingGraph();Two differences matter in practice:
join fetchis an inner join. Authors with no books disappear from the result. Useleft join fetchto keep them. An@EntityGraphuses a left outer join by default, so authors without books remain.- A
join fetchmust be written into every query that needs it. A graph on a repository method is attached to that method, which is easier to see in code review.
When batch fetching wins
Batch fetching is the best default when you cannot predict which association a caller will touch. You set one property and every lazy collection or proxy is loaded for up to 50 parents at a time.
spring.jpa.properties.hibernate.default_batch_fetch_size=50Choose it in these cases:
- The query returns a page of parents, because paging stays in SQL and no collection join is involved.
- The code path touches several collections. Fetch joins on more than one collection cause the multiple-bag problem, while batch fetching handles each collection with its own statement.
- You want protection against N+1 across the whole application without editing every query.
Its cost is that you still run more than one statement per request. For 1000 authors with a batch size of 50, you get about 21 statements instead of 1001. That is a large gain, but one joined query would be fewer.
When a DTO projection wins
Pick a projection when the screen or API needs a few columns, or an aggregate such as a count. Loading every author and every book just to compute books.size() is wasteful, because the database can count for you.
public record AuthorBookCount(String name, Long bookCount) {}
public interface AuthorStatsRepository extends JpaRepository<Author, Long> {
@Query("""
select new com.example.AuthorBookCount(a.name, count(b))
from Author a left join a.books b
group by a.id, a.name
""")
List<AuthorBookCount> findAuthorBookCounts();
}The cost is one query method and one record per use case. Teams often accept that for read-heavy endpoints. Do not use projections on write paths where you need dirty checking.
Collections and paging
When the result is paged and you need a collection, a collection join fetch is the wrong choice. Hibernate cannot apply limit to a joined result without cutting a parent's children, so it loads everything and pages in memory. It logs a warning about this. Pick one of these instead:
- Batch fetching on top of an ordinary paged parent query.
- A two-step query: page the ids in SQL, then fetch the parents and their books for those ids.
- A projection that returns only the columns you need.
The two-step version looks like this:
public interface AuthorRepository extends JpaRepository<Author, Long> {
@Query("select a.id from Author a")
Page<Long> findAuthorIds(Pageable pageable);
@Query("select distinct a from Author a left join fetch a.books where a.id in :ids")
List<Author> findWithBooksByIdIn(@Param("ids") List<Long> ids);
}The second query does not guarantee order. Reorder the results by the id list if the page order matters.
For two or more collections on the same entity, avoid fetching them in one query. Fetch one collection by join and let batch fetching handle the others, or run separate queries in the same transaction. Separate queries return the same managed entities from the persistence context, so the second query fills in the second collection.
Combine strategies
The strategies are not exclusive. A common setup is:
default_batch_fetch_size=50set globally as a safety net.@EntityGraphorjoin fetchon the hot read paths where you know exactly what is needed.- DTO projections for list screens and reports.
Pair this with a query-count test, shown in the earlier chapter on regression tests, so a change that reintroduces N+1 fails the build.
Worked example
Consider three requirements for the author and book model.
- Admin page: list of 20 authors per page, each with a book count. Use the projection. Nothing needs to be modified, and the count is computed by the database. A paged projection query returns the page in one statement.
- Author detail page: one author with all books, then edit the author's name. Use
@EntityGraphon afindById-style method, orleft join fetchwith awhere a.id = :id. You modify the entity, so you need a managed one. Only one author is loaded, so there is no paging problem. - Public API: page of 20 authors, each with its book titles, read only. A DTO query is possible, but if the response is a nested structure, use the two-step query or batch fetching. The paged parent query stays in SQL, and the books load in one extra statement for the whole page.
In all three cases the aim is a small, predictable statement count that does not grow with the number of rows.
Common errors when choosing
- Setting
FetchType.EAGERas the fix. Eager mapping applies to every query, including ones that do not need the association, and can still issue extra statements when you query by JPQL. Fetch per query instead. - Using
join fetchon a paged query. The result looks correct, but Hibernate loads all rows into memory. - Fetching two collections in one query. This causes the multiple-bag error or a large cartesian product.
- Returning entities from a read-only endpoint. A projection is cheaper and removes the lazy loading risk.
- Choosing without measuring. Check the statement count with Hibernate statistics before and after the change.
Exercise
An endpoint returns page 3 of authors (20 per page), each with its book titles, and never modifies them. A teammate proposes select a from Author a join fetch a.books with a Pageable. Explain what goes wrong and name two better options.
Show answer
With a collection join fetch, Hibernate cannot apply the page limit in SQL without truncating each author's books, so it loads every matching row and pages in memory, which is slow and memory heavy. It also uses an inner join, so authors with no books vanish. Better options are a DTO projection that selects only the needed columns, or paging author ids in SQL and then fetching those authors with left join fetch. Batch fetching on a normal paged author query also works.
Exercise
A screen needs every author, including authors with no books, and must edit the author name and save it. Which strategy fits, and which detail of the fetch must you get right?
Show answer
Use managed entities, because dirty checking is needed to save the change. Use @EntityGraph(attributePaths = "books") or left join fetch a.books. The detail is the join type: an inner join fetch would drop authors with no books, while left join fetch or the entity graph's left outer join keeps them.