Fix the Hibernate N Plus 1 Query Problem in Spring Data JPA
Detect the Hibernate N plus 1 query problem with a statement count, then remove it with a fetch join, an entity graph or batch fetching.

A page that lists fifty orders and their customers runs fifty-one queries. Nobody notices until the table has fifty thousand rows. The pattern is called N plus 1: one query loads the list, then each row triggers its own query for a lazy association. This post shows how to prove you have it and the four ways to remove it on Hibernate 7 and Spring Data JPA, from the cheapest change to the most flexible. The mapping rules behind it are in Hibernate and JPA without the surprises.
Prove it with a statement count
Logs help, but a failing test keeps it fixed. Hibernate exposes counters through Statistics:
@DataJpaTest
class OrderListQueryTest {
@Autowired EntityManager em;
@Test
void loadingOrdersWithCustomersUsesOneStatement() {
var stats = em.getEntityManagerFactory().unwrap(SessionFactory.class).getStatistics();
stats.setStatisticsEnabled(true);
stats.clear();
em.createQuery("select o from Order o join fetch o.customer", Order.class)
.getResultList()
.forEach(o -> o.getCustomer().getName());
assertEquals(1, stats.getPrepareStatementCount());
}
}Remove join fetch and the count becomes one plus the number of distinct customers, so the test fails. To see the statements as they run, set logging.level.org.hibernate.SQL=debug in a dev profile.
Fix 1: join fetch
@Query("select o from Order o join fetch o.customer where o.status = :status")
List<Order> openWithCustomer(@Param("status") OrderStatus status);One query, one join. This is the right default for a to-one association you always need together.
Fix 2: entity graph
An entity graph keeps the repository method name clean and chooses the fetch plan per method:
@EntityGraph(attributePaths = {"customer"})
List<Order> findByStatus(OrderStatus status);It produces the same SQL as the join fetch. Pick whichever your team finds easier to read.
Fix 3: batch fetching
When the association is only sometimes read, or when the caller decides, batching turns N lazy loads into a few:
spring:
jpa:
properties:
hibernate:
default_batch_fetch_size: 16With a batch size of 16, loading the customers for fifty orders takes four in (?, ?, ...) queries instead of fifty. It is a safety net, not a design: you still pay more than one query.
Fix 4: a projection
If a screen shows an order number and a customer name, load exactly that:
public record OrderRow(long id, String customerName) {}
@Query("select new dev.javahacks.shop.OrderRow(o.id, c.name) from Order o join o.customer c")
List<OrderRow> rows();No entity, no proxy, no lazy association. For read-only lists this is the cleanest answer.
Collections need more care
Joining a collection multiplies rows, one per child, so a join fetch over lines returns each order as many times as it has lines. Hibernate deduplicates the entities, but pagination breaks down. Combining a collection fetch with setMaxResults makes Hibernate apply the limit in memory after loading every row, and it logs a warning saying so. Page the ids first with one query, then fetch the entities for that page with a second. Fetching two collections at once fails with [MultipleBagFetchException](/library/multiplebagfetchexception-fix-fetch-joins-batching).
Which fix when
| Situation | Use |
|---|---|
| Always need the to-one association | join fetch or @EntityGraph |
| Read-only list or API response | DTO projection |
| Caller decides what it reads | Batch fetch size as a safety net |
| Paginated list with a collection | Two queries: ids, then entities |
Make the count a failing test
A query count that nobody checks grows back. A test that fails when a use case runs more statements than expected keeps it fixed. Hibernate's statistics are enough:
@DataJpaTest
@Import(OrderQueries.class)
class OrderQueriesTest {
@Autowired EntityManager em;
@Autowired OrderQueries queries;
@Test
void listWithCustomersUsesOneStatement() {
Statistics stats = em.getEntityManagerFactory().unwrap(SessionFactory.class).getStatistics();
stats.setStatisticsEnabled(true);
stats.clear();
queries.latestWithCustomers(50).forEach(o -> o.getCustomer().getName());
assertThat(stats.getPrepareStatementCount()).isEqualTo(1);
}
}The test loads 50 orders and touches each customer's name, which would run 51 statements in the broken version. Set the expected number to what the correct query needs, and every later change is held to it. A library such as datasource-proxy or the SQL statement counter in Hypersistence Utils offers the same check with a nicer failure message.
Batch fetching as a safety net
A global batch size does not remove the problem, and it turns 51 statements into 4 when a fix has not been applied yet:
spring.jpa.properties.hibernate.default_batch_fetch_size=16With it, when one lazy association of a customer is touched, Hibernate loads the same association for up to 16 customers at once, using an in list. Fifty orders touching their customers need 1 plus ceil(50 / 16) = 4 statements. That is better than 51 and worse than the single join query, so treat it as a floor under all queries and still fix the hot ones with a fetch join. The size 16 is a starting point, and values between 10 and 50 are common.
Pagination and collection fetches
A fetch join on a collection multiplies rows, one per child, and a page limit applied to those rows cuts parents in half. Hibernate warns about it and pages in memory:
HHH90003004: firstResult/maxResults specified with collection fetch; applying in memoryLoading every parent and every child of the table, then cutting a page in the application, is the worst outcome. Avoid it with two queries: the first selects the ids of one page of parents, and the second fetches those parents with their collections.
List<Long> ids = em.createQuery("select o.id from Order o order by o.id desc", Long.class)
.setMaxResults(50).getResultList();
List<Order> orders = em.createQuery(
"select distinct o from Order o left join fetch o.lines where o.id in :ids order by o.id desc", Order.class)
.setParameter("ids", ids).getResultList();Both queries use the database for what it does well, and the second returns exactly 50 parents with their lines. Fetching two collections in one query yields a cartesian product and a MultipleBagFetchException for lists, so fetch one collection per query.
Find it in production, not only in tests
The pattern leaves a signature in the database: the same statement with a different parameter, executed hundreds of times in one request. The slow query log shows nothing, because each statement is fast, and the aggregate by statement text does. In PostgreSQL, pg_stat_statements sorted by calls brings it to the top. An APM trace with the span count per request shows it as a staircase of identical database spans. Alert on spans per request, not on slow queries.
| Tool | What it shows |
|---|---|
pg_stat_statements ordered by calls | The statement run most often |
| APM trace | Many identical database spans in one request |
hibernate.generate_statistics | Statement and entity load counts per session |
| Test with a counter | A regression before it ships |
Write the rule for your team
The pattern comes back whenever someone adds a field to a screen. Agree on a rule and enforce it: every list endpoint has a test that counts statements, every new association is lazy by default, and every query that returns a collection of entities states how its associations are fetched, with a fetch join, an entity graph or a projection. The rule fits on an index card and a review checklist.
With the test in place, the discussion in a pull request changes from "is this slow?" to "the count went from 2 to 52", which is a fact and not an opinion, and it ends in one comment.
Where batching and fetch joins are not enough
If a report reads hundreds of thousands of rows across many tables, no ORM fetch plan is the right tool. Use SQL through JDBC or a native query and map the rows yourself. The exception that pushes teams toward eager mapping, [LazyInitializationException](/library/lazyinitializationexception-fix-spring-boot-hibernate), is the same lesson from the other direction. The primary sources are the Hibernate ORM documentation and the Spring Data JPA reference.


