Articles Spring

JPA N+1 problem: three ways to fix it in Hibernate

The N+1 problem in JPA is one query that loads a list of N entities, followed by N more queries that load an association of each entity, one row at a time. You fix it by telling Hibernate to load the association together with the list: with JOIN FETCH in JPQL, with @EntityGraph on a Spring Data repository method, or with batch fetching (@BatchSize or hibernate.default_batch_fetch_size). Switching the mapping to FetchType.EAGER does not fix it.

All numbers below come from one small project: Spring Boot 4.1.1 with Hibernate ORM 7.4.5 and H2, 10 authors with 3 books each. Where Spring Boot 3.5 (Hibernate 6.6) behaves differently, it is called out.

What is the N+1 query problem in JPA?

Two entities, with a lazy collection on the parent side:

@Entity
class Author {
    @Id @GeneratedValue Long id;
    String name;
    @OneToMany(mappedBy = "author") List<Book> books = new ArrayList<>();
}

@Entity
class Book {
    @Id @GeneratedValue Long id;
    String title;
    @ManyToOne(fetch = FetchType.LAZY) Author author;
}

The code that triggers the problem looks innocent:

List<Author> authors = authorRepository.findAll();
for (Author a : authors) {
    total += a.getBooks().size(); // first touch of the lazy collection
}

With logging.level.org.hibernate.SQL=DEBUG the log shows one select for the authors and then the same select once per author:

select a1_0.id,a1_0.name from author a1_0
select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id=?
select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id=?
-- ... 8 more identical lines

That is 11 statements for 10 authors. With 1000 authors it is 1001, and each one is a network round trip. The queries are fast on their own, which is why the problem hides in development and shows up under production data volumes.

Does FetchType.EAGER fix the N+1 problem?

No. EAGER changes when the extra selects run, not how many there are. For a JPQL or repository query Hibernate executes the query as written and then loads every eager association with a secondary select. The Hibernate user guide says so directly: the fetch policy of an entity query cannot be overridden, so a secondary select is required.

With @OneToMany(fetch = FetchType.EAGER) on the collection, select a from Author a still produced 11 statements. Only em.find(Author.class, id) used a single joined select.

The same applies in the other direction, and here the default bites. @ManyToOne and @OneToOne are EAGER unless you say otherwise (the Jakarta Persistence Javadoc: “If not specified, defaults to EAGER”). Selecting 30 books with a default @ManyToOne author ran 1 + 10 statements: one for the books and one per distinct author. Declare to-one associations LAZY and fetch them per query.

Fix 1: JOIN FETCH in JPQL

A fetch join loads parent and children in one statement:

@Query("select a from Author a join fetch a.books")
List<Author> findAllWithBooks();
select a1_0.id,b1_0.author_id,b1_0.id,b1_0.title,a1_0.name
from author a1_0 join book b1_0 on a1_0.id=b1_0.author_id

One statement, 10 authors, 30 books. Since Hibernate 6 the result list holds each author once, so distinct is no longer needed. Note the inner join: authors without books drop out of the result. Use left join fetch to keep them.

JOIN FETCH with pagination

Paging over a collection fetch join used to be a trap. On Spring Boot 3.5 (Hibernate 6.6.53) and on Spring Boot 4.0 (Hibernate 7.2.1) a Pageable on the query above logs this warning:

WARN org.hibernate.orm.query : HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory

The SQL then has no limit at all. Hibernate reads every author with every book and cuts the page out in the JVM. Setting hibernate.query.fail_on_pagination_over_collection_fetch=true turns the warning into an exception, which is the safer choice on those versions.

Hibernate 7.4, which Spring Boot 4.1 brings, changed this. The What’s New in 7.4 notes describe limits combined with collection fetch joins as safe on every database that supports limits in subqueries. The same repository method on Boot 4.1.1 logged no warning and pushed the page into a subquery:

select a1_0.id,b1_0.author_id,b1_0.id,b1_0.title,a1_0.name
from (select a1_0.id,a1_0.name from author a1_0
      where exists(select 1 from book b1_0 where a1_0.id=b1_0.author_id)
      order by a1_0.id offset ? rows fetch first ? rows only) a1_0(id,name)
join book b1_0 on a1_0.id=b1_0.author_id order by a1_0.id

MultipleBagFetchException with two List collections

Fetch-joining two List collections of the same entity fails before any SQL is sent:

org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: [demo.Author.awards, demo.Author.books]

A List without an order column is a bag, and two joined bags produce a cartesian product that Hibernate cannot untangle. Changing the fields to Set makes the exception go away but keeps the cartesian product (3 books times 2 awards gives 6 rows per author). The cleaner fix is to fetch-join one collection and load the other with batch fetching.

Fix 2: @EntityGraph on a Spring Data repository method

@EntityGraph states which associations to load without writing the join yourself. It works on derived query methods, on @Query methods and on overridden methods such as findAll:

@EntityGraph(attributePaths = "books")
@Query("select a from Author a")
List<Author> findAllWithBooksGraph();
select a1_0.id,b1_0.author_id,b1_0.id,b1_0.title,a1_0.name
from author a1_0 left join book b1_0 on a1_0.id=b1_0.author_id

One statement again, this time with a left join, so authors without books stay in the result. The Spring Data JPA reference covers named graphs as well. Underneath it is the same mechanism as a fetch join, so the same rules apply: the pagination warning on Hibernate 6.6 and 7.2, the subquery on 7.4, and MultipleBagFetchException for two bags.

Fix 3: batch fetching with @BatchSize or default_batch_fetch_size

Batch fetching keeps the association lazy but loads it for several parents at once. Put @BatchSize(size = 25) on the collection, or set a global default:

spring.jpa.properties.hibernate.default_batch_fetch_size=4

The size of 4 is deliberately tiny to make the batches visible. The loop from the first section, unchanged, now produced:

select a1_0.id,a1_0.name from author a1_0
select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id in (?,?,?,?)
select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id in (?,?,?,?)
select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id in (?,?,?,?)

Four statements for 10 authors: 1 + ceil(N / size). It is not a single query, but it has two advantages. Pagination stays in SQL on every Hibernate version, because the first query has no collection join, and any number of collections can be batched without a cartesian product. A page of 5 authors took 3 statements here, against 6 without batching.

When is a DTO projection the better fix?

If the code only reads data, skip entities altogether. A constructor expression selects exactly the columns the screen needs, with no lazy associations left to trigger anything:

@Query("select new demo.AuthorTitle(a.name, b.title) from Author a join a.books b")
List<AuthorTitle> findAuthorTitles();

AuthorTitle is a plain record. The query ran as one statement that returned 30 rows of two columns.

How do you detect N+1 queries?

  • Log the SQL in development: logging.level.org.hibernate.SQL=DEBUG (or spring.jpa.show-sql=true). A block of identical selects that differ only in the bound id is the signature.
  • Count statements in tests. With spring.jpa.properties.hibernate.generate_statistics=true Hibernate keeps counters you can assert on, so a regression fails the build:
Statistics stats = entityManagerFactory.unwrap(SessionFactory.class).getStatistics();
stats.clear();

List<Author> authors = authorRepository.findAllWithBooks();
authors.forEach(a -> a.getBooks().size());

assertThat(stats.getPrepareStatementCount()).isEqualTo(1);
  • Keep spring.jpa.open-in-view=false. With it enabled, lazy loading during view or JSON rendering works silently and hides the problem instead of failing with LazyInitializationException.

Which N+1 fix should you use?

Measured statement counts for 10 authors with 3 books each:

VariantStatementsUse it when
Lazy collection in a loop11Never for a list
FetchType.EAGER with a query11Never as a fix
JOIN FETCH1One collection, a query you write yourself
@EntityGraph1Same, on a derived or inherited repository method
Batch fetching, size 44Several collections, paging on Hibernate before 7.4, a safe global default
DTO projection1Read-only views and reports

Summary

N+1 is a fetch plan problem, not a mapping problem. Keep associations LAZY, including @ManyToOne, and decide per use case what to load. Use JOIN FETCH or @EntityGraph for a single collection, batch fetching as the default safety net and for multiple collections, and a DTO projection when you only read. Before Hibernate 7.4, never page over a collection fetch join. Then pin the result with a statement count assertion, because the next innocent getter call in a loop brings the problem back.