Sub topic 4
How the N+1 select problem happens
This chapter assumes you can read JPA entity mappings, write a Spring Data repository, and read basic SQL. It uses the Author and Book model from the earlier chapters. An author has many books, and each book points back to one author.
The setup: lazy collections
Author.books is a @OneToMany collection, and JPA loads those by default only when you first use them. Hibernate puts an uninitialized collection wrapper in the field. The wrapper runs a SQL query the first time your code reads from it. Book.author is declared FetchType.LAZY for the same reason.
Lazy loading is a good default. The cost shows up when you touch the lazy association inside a loop.
The code that triggers it
@Service
public class AuthorService {
private final AuthorRepository authorRepository;
public AuthorService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Transactional(readOnly = true)
public List<String> authorSummaries() {
return authorRepository.findAll().stream()
.map(a -> a.getName() + ": " + a.getBooks().size())
.toList();
}
}Nothing in this code looks wrong. It still produces more SQL than you might expect.
What happens step by step
findAll()runsselect ... from author. This is the "1" query. It returns N authors, and each one has an uninitializedbookscollection.- The stream visits the first author.
getBooks()returns the wrapper, andsize()forces it to load. Hibernate runsselect ... from book where author_id = ?for that author. - The wrapper is now initialized and stored in the persistence context.
- The stream moves to the next author, whose collection is still uninitialized. Hibernate runs another query.
- This repeats for each of the N authors.
With 100 authors, one method call sends 101 statements. The total is 1 + N, which is where the name comes from.
Why the persistence context does not help
The persistence context is a per-transaction cache of loaded entities. It can avoid loading the same entity twice. It cannot combine the loads of different authors' collections, because each collection is a separate lazy load keyed by a different author_id. Each one is a cache miss, so each one reaches the database.
Why it stays hidden
- Tests often use two or three rows, so the extra queries cost almost nothing.
- Each query is fast, so no single one stands out in a slow-query log.
- The cost is network round trips, and it grows with the data.
- The problem sits in a mapping and a loop, not in an obvious SQL string.
The same pattern appears with @ManyToOne. If you load 100 books and read book.getAuthor().getName() for each, you can get one query per distinct author.
Common mistakes
- Switching to
FetchType.EAGER. This does not remove N+1. AfindAll()on an entity with an eager association still often loads the association with extra queries. It also loads that data in every query that touches the entity, including ones that do not need it. - Blaming the loop. The loop is only where the access happens. The cause is a query that loads parents without telling Hibernate which associations it needs.
- Assuming a transaction fixes it. A transaction keeps the session open so lazy loading works. It does not reduce the number of statements.
The next chapter shows how to count the statements so you can confirm the problem instead of guessing.
Exercise
A page lists 40 authors and prints each author's book count using getBooks().size() inside a read-only transaction. How many SQL statements run, and why does the persistence context not reduce them?
Show answer
41 statements: one select for the authors and one select per author to initialize that author's lazy books collection. The persistence context only caches entities it has already loaded. Each author's collection is a separate lazy load with a different author_id, so none of them are cached and each one goes to the database.