Sub topic 4
How the N+1 select problem happens
This chapter assumes you can read a JPA entity mapping, write a Spring Data repository, and follow a simple SQL join. It builds on the previous chapters: the Author and Book model, the persistence context, and lazy versus eager fetching. Here you will see exactly how those pieces combine to produce one query plus N more.
What N+1 means
The N+1 select problem is a pattern where your code issues one query to load a list of N parent rows, then issues one additional query for each parent to load related data. The total is 1 + N statements, where a single joined query or two simple queries would have been enough.
Each statement is cheap on its own. The cost comes from multiplying round trips to the database. With 10 authors the extra queries go unnoticed. With 5,000 authors, you send 5,001 statements, each with network latency, parsing, and connection time.
The model
The example uses two entities. An Author has many Book rows. Author.books is a @OneToMany collection, which is lazy by default. Book.author is a @ManyToOne that is explicitly set to lazy.
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "author")
private List<Book> books = new ArrayList<>();
public Long getId() { return id; }
public String getName() { return name; }
public List<Book> getBooks() { return books; }
}
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@ManyToOne(fetch = FetchType.LAZY)
private Author author;
public Long getId() { return id; }
public String getTitle() { return title; }
public Author getAuthor() { return author; }
}Because books is lazy, loading an Author does not load its books. Hibernate puts a placeholder collection in the books field. The placeholder holds the author's id and runs a query the first time you touch its contents.
The code that triggers it
The following service looks harmless. It lists each author with a book count.
@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();
}
}findAll() runs one query for the authors. Then a.getBooks().size() is called inside the stream, once per author. Calling size() on an uninitialized lazy collection forces Hibernate to initialize it, and that sends one select ... from book where author_id = ? statement. For N authors you get 1 + N statements.
Step by step
The sequence below shows what happens for three authors.
The database log for this run would look like this, with 4 statements for 3 authors:
select a.id, a.name from author aselect b.author_id, b.id, b.title from book b where b.author_id=?with 1- The same statement with 2
- The same statement with 3
Why the persistence context allows it
Lazy loading only works while the entity is managed, meaning it is attached to an open persistence context. The @Transactional annotation on authorSummaries() keeps the session open for the whole method. Each lazy collection holds a reference to that session and uses it to run its query on demand.
This is why N+1 often appears in code that "works". There is no exception and no wrong result. The persistence context quietly answers every lazy access with a new query, and the method returns correct data, only slowly.
The persistence context does help in one case. If the same entity or collection is requested twice in a session, Hibernate serves the second request from its first-level cache without another query. So the repeated cost is per distinct parent, not per access. Two authors sharing the same lazy Book.author reference would load that author once.
Where else N+1 appears
The Author.books collection is the common case, but the same mechanism applies to several mappings.
| Access pattern | Trigger | Queries |
|---|---|---|
| Lazy `@OneToMany` collection read for each parent | `author.getBooks().size()` or iteration | One per parent |
| Lazy `@ManyToOne` read for each child | `book.getAuthor().getName()` over a list of books | One per distinct author |
| `@ManyToOne` or `@OneToOne` with `FetchType.EAGER` | Loading a list of children via JPQL or a derived query | One per distinct parent, right after the main query |
| Nested lazy access | `author.getBooks()` then `book.getReviews()` | Compounds, 1 + N + M |
Note the third row. The JPA default for @ManyToOne and @OneToOne is EAGER. If you did not set LAZY on Book.author, then findAll() on books would run the main query and then immediately fire one query per distinct author. Eager fetching does not prevent N+1. For JPQL and derived queries it often causes it, because the query itself does not join the association.
A related surprise: em.find(Book.class, id) and findById load an eager association with a join. A JPQL query like select b from Book b does not. The same mapping gives different SQL depending on how you load the entity.
Spotting the pattern in code review
Look for these signs in a service or controller method:
- A repository call that returns a list, followed by a loop, stream, or mapper that reads an association.
- A mapper (such as a MapStruct or hand-written DTO converter) that copies
getBooks()orgetAuthor()for each entity. - A
toString(),equals(), or JSON serializer that walks associations. - A
size(),isEmpty(), orstream()call on a lazy collection inside a loop.
Serialization is a frequent hidden cause. Returning entities from a controller lets Jackson walk every getter, which initializes each lazy collection. With Open Session in View on, this works without errors and produces N+1 outside your service layer. A later chapter covers that setting.
Cost model
The number of statements is easy to predict:
- Parent query: 1
- Lazy collection per parent: N, or fewer if parents repeat
- Second-level nesting: N × M for M children each with their own lazy collection
The time cost is roughly the statement count times the round-trip latency, plus per-statement overhead. A call that takes 1 ms against a local database may take 5 to 20 ms across a network. At 10 ms and 1,000 authors, the extra queries alone cost around 10 seconds. Load also scales with concurrency, since each statement uses a pooled connection for its duration.
Common mistakes
- Assuming
@Transactional(readOnly = true)prevents the extra queries. It only keeps the session open. It does not change fetching. - Switching associations to
EAGERto "fix" it. That moves the problem and makes every load fetch associations, including loads that do not need them. - Testing only with a handful of rows. N+1 grows linearly, so small test data hides it.
- Judging performance by response time on a local machine rather than by statement count.
What comes next
You now know the cause: a list query plus lazy access per row, running inside an open persistence context. The next chapter shows how to measure it with SQL logging and Hibernate statistics, so that you can confirm it in your own code before applying a fix.
Exercise
A method loads List<Book> books = bookRepository.findAll() and then prints book.getAuthor().getName() for each book. The 200 books have 20 distinct authors, Book.author is LAZY, and the method runs in one transaction. How many SQL statements run, and why is it not 201?
Show answer
21 statements. One statement loads the 200 books. Each distinct author is loaded once by a select on the author table when its proxy is first accessed. After that, the persistence context returns the already loaded author for any other book that points to the same id, so it does not query again. The count is 1 + the number of distinct authors, not 1 + the number of books.
Exercise
A teammate says that adding fetch = FetchType.EAGER to Author.books will fix the N+1 in authorSummaries(). Does it? What would you expect to see in the SQL log?
Show answer
No. A findAll() derived query is translated to JPQL, which does not join the eager collection. Hibernate runs the author query first and then loads the collection for each author with a separate select, so you still see 1 + N statements. The change also makes every other load of Author fetch its books, including places that do not need them.