The N+1 Problem in JPA: Fetch Types, Join Fetch and Entity Graphs
Relay's ticket list of 50 tickets quietly sends 51 queries. Count them with Hibernate statistics, bring it down to 1 with a left join fetch or an entity graph, and see why EAGER still sends 51.
What you will learn
- Map @OneToMany and @ManyToOne and know what LAZY means
- Count the queries a page sends with Hibernate statistics
- Fix an N+1 list with left join fetch or @EntityGraph
- Explain why FetchType.EAGER does not fix it
Before you start
- JPA Entity Mapping: Ids, Enums and Dates
- Spring Data Query Methods: Derived Queries, @Query and Projections
The agents' ticket list in Relay shows 50 tickets, each with its comment count. The page looks perfectly fine. Then you look at the SQL log: 51 queries to draw one screen. Nothing breaks, nothing is red, and that's exactly why this problem is so easy to miss.
This is the N+1 problem: one query for the list, plus one more for every row. Let's reproduce it, count it, and bring it down to one query.
One ticket, many comments
It starts with how a ticket holds its comments. In the Ticket entity:
// LAZY: the customer row is read only when somebody asks for it
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "customer_id")
private Customer customer;
// nullable: a new ticket has nobody assigned yet
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "assignee_id")
private Agent assignee;
@OneToMany(mappedBy = "ticket")
@OrderBy("createdAt") // oldest message first
private List<Comment> comments = new ArrayList<>();
And each Comment points back to its ticket:
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "ticket_id")
private Ticket ticket;
@OneToMany(mappedBy = "ticket") says the foreign key lives on the comment side, in ticket_id. We didn't write a fetch type on the list, and a @OneToMany is lazy by default. Lazy means: load it when somebody uses it, not before.
Count the queries
To see the problem you need a number, not a feeling. Turn on Hibernate statistics in application.yaml with spring.jpa.properties.hibernate.generate_statistics: true (and logging.level.org.hibernate.SQL: debug to see each statement). Then a small runner loads the list and counts:
@Component
public class TicketListRunner implements CommandLineRunner {
private final TicketRepository tickets;
private final EntityManagerFactory factory;
private final String how; // lazy, join or graph
public TicketListRunner(TicketRepository tickets, EntityManagerFactory factory,
@Value("${relay.list:lazy}") String how) {
this.tickets = tickets;
this.factory = factory;
this.how = how;
}
@Override
@Transactional(readOnly = true)
public void run(String... args) {
SessionFactory sf = factory.unwrap(SessionFactory.class);
Statistics stats = sf.getStatistics();
stats.clear();
List<Ticket> list = switch (how) {
case "join" -> tickets.findAllWithComments();
case "graph" -> tickets.findAllWithGraph();
default -> tickets.findAllByOrderById();
};
for (Ticket t : list) {
var n = t.getComments().size();
System.out.println(t.getSubject() + " | comments: " + n);
}
System.out.println("Queries: " + stats.getPrepareStatementCount());
}
}
With the plain derived query findAllByOrderById() (50 tickets, 80 comments, PostgreSQL 18):
Cannot log in after password reset | comments: 2
Invoice shows the wrong amount | comments: 2
...
Queries: 51
Scroll up in the log and you see one select ... from ticket, then select ... from comment where ticket_id=? fifty times.
Where the 50 extra queries come from
Each Ticket comes back with a proxy in place of its comments. When the loop calls getComments().size(), the proxy has nothing, so Hibernate sends a select for that one ticket. Fifty tickets, fifty selects, plus the first one.
Fix 1: left join fetch
// fix 1: ask for the comments in the same query
@Query("from Ticket t left join fetch t.comments order by t.id")
List<Ticket> findAllWithComments();
join fetch loads every ticket and its comments in one statement. It's a left join so a ticket with no comments yet still appears. Run with --relay.list=join: the same 50 lines, then Queries: 1.
Fix 2: an entity graph
// fix 2: the same idea as an entity graph
@EntityGraph(attributePaths = "comments")
@Query("from Ticket t order by t.id")
List<Ticket> findAllWithGraph();
@EntityGraph names the fields to load up front, and Hibernate writes the join for you. The query underneath stays plain. Run with --relay.list=graph: Queries: 1.
Break it: EAGER is not the fix
A common first thought is "make it eager":
@OneToMany(mappedBy = "ticket", fetch = FetchType.EAGER)
Run the plain list again: still Queries: 51. Eager only moves the same fifty selects to the moment the tickets load. Worse, now every query that loads a ticket pays for its comments, even screens that never show them. Undo it.
The same trap on a real page
In the Relay app, one customer's page with 14 tickets, loaded lazily, needed 20 SQL statements: one for the customers, one for the tickets, fourteen for the comments, three for the assignees, and one for the agent list. With the fetch join, the same page needed 3. The page looked exactly the same both times. Only the log could tell.
Four ways to load the same list
| Way | When comments load | Queries for 50 tickets |
|---|---|---|
| LAZY (default) | when the loop asks | 51 |
| EAGER | whenever a ticket loads | 51 |
left join fetch | in the same query | 1 |
@EntityGraph | in the same query, named by annotation | 1 |
So keep relationships lazy, and for the screens that need the related data, ask for it in that screen's query.
Common mistakes
- Judging by the page. 1 query and 51 queries look the same in the browser. Turn on statistics or the SQL log and count.
- Plain
join fetchinstead ofleft join fetch. Tickets without comments disappear from the list. - Switching to EAGER. Same count, and now every ticket query pays for it.
- Fixing only the comments.
getCustomer()andgetAssignee()in the same loop are lazy too, and add their own selects.
Try it yourself
In the runner, change t.getComments().size() to t.getCustomer().getName() and run the lazy list. You should see Queries: 6: one for the tickets, then one per distinct customer. There are only 5 customers, and a customer that's already loaded isn't loaded twice. How would you make it 1?
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
A one-line JpaRepository interface and a small @Service class save and read blog posts with no SQL. Follow one save and one read through every layer, then prove it with a test.
Entities and H2 in Spring Boot: a Post Class Becomes a Table
The blog's cards are typed into HTML. A Post class with @Entity and @Id becomes the POST table in an in-memory H2 database: three pom lines, a few YAML settings, and Hibernate writes the create table SQL at startup.
Seed Data and Posts on the Homepage: CommandLineRunner, the Model and th:each
SeedData, a CommandLineRunner, saves three posts when the POST table is empty. HomeController puts postService.getAll() into the Model, and one postCard inside th:each becomes three cards. Three inserts at startup, one select per visit.
Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
Eight posts, three to a page, newest first. HomeController turns ?page=1&sort=oldest into a PageRequest, PostService passes it to findAll(Pageable), H2 runs one select with an offset and one count, and the Page that comes back knows it is page 2 of 3.
