Originally published at Shipped Code.

A list endpoint that answers instantly on your laptop can crawl once it meets real data, and the log fills up with near-identical select statements. In Spring Data JPA that is usually the N+1 problem. In the example below, GET /authors returns 10 authors with 3 books each and runs 11 SQL statements. Loading the books in the same query brings it down to 1.

TL;DR. Turn on the org.hibernate.SQL logger and look for 1 query for the list followed by N copies of the same child query. Fix it with left join fetch a.books or @EntityGraph (11 statements become 1), or with hibernate.default_batch_fetch_size, which batches the N queries and leaves paging alone. Then add a test that asserts the statement count with Hibernate Statistics, so CI fails when N+1 returns.

What you'll learn:

  • how to spot N+1 in the Hibernate 7 log, including when it starts in a mapper;
  • which fix fits which list: JOIN FETCH, @EntityGraph, batch fetching or a two-step query;
  • how to write a test that fails when the statement count goes up.

To fix the N+1 in front of you, read up to Fix 3, then the sections on choosing a fix and on the test; the (Advanced) sections are for large paged lists. You should have written JPA entities before (the Java backend roadmap shows where that fits). Examples run on Spring Boot 4.2, Hibernate ORM 7.4, Java 25 and PostgreSQL 18.

What an N+1 query looks like

N+1 means your code runs 1 query to load N parent rows, then N more queries, one per parent, to load each parent's children.

Flow of an N+1 query: GET /authors runs 1 SELECT on author, then every time an Author is mapped to an AuthorDto, getBooks() runs 1 more SELECT on book; 10 authors give 11 SQL statements in total

The example uses 2 tables, author and book; data.sql uses generate_series, so it needs PostgreSQL. A real project would manage the schema with Flyway migrations, not ddl-auto.

create table author ( id bigserial primary key, name varchar(100) not null ); create table book ( id bigserial primary key, title varchar(200) not null, author_id bigint not null references author (id) ); 
insert into author (name) select 'Author ' || g from generate_series(1, 10) g; insert into book (title, author_id) select 'Book ' || a.id || '-' || b, a.id from author a, generate_series(1, 3) b; 

@OneToMany is LAZY by default, so Hibernate loads the books only when code calls getBooks(). Book maps author_id with @ManyToOne(fetch = FetchType.LAZY). Snippets leave out imports and accessors.

@Entity public class Author { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @OneToMany(mappedBy = "author") // LAZY by default private List<Book> books = new ArrayList<>(); } 

GET /authors returns service.listAuthors(), which maps each author to a DTO.

@Service @Transactional(readOnly = true) public class AuthorService { private final AuthorRepository repo; public AuthorService(AuthorRepository repo) { this.repo = repo; } public List<AuthorDto> listAuthors() { return repo.findAll().stream().map(AuthorDto::from).toList(); } } 
public record AuthorDto(String name, List<String> books) { static AuthorDto from(Author a) { return new AuthorDto(a.getName(), a.getBooks().stream().map(Book::getTitle).toList()); // touches books here } } 

Lazy loading works here because @Transactional(readOnly = true) keeps the session open while the mapper runs. Map outside a transaction with open-in-view off and Hibernate 7 throws LazyInitializationException: Cannot lazily initialize collection of role '...Author.books' with key '1' (no session). With the default open-in-view=true, lazy loading works all the way into the controller, and Boot logs a startup WARN about it.

One request to GET /authors produces this log.

org.hibernate.SQL : select a1_0.id,a1_0.name from author a1_0 org.hibernate.SQL : select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id=? org.hibernate.SQL : select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id=? ... 7 more identical lines org.hibernate.SQL : select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id=? 

No code loops over a repository call. The 10 from book queries come from AuthorDto.from() touching getBooks() on each author.

Find N+1 in the log

To see N+1, turn on Hibernate's SQL logger and statistics. On Hibernate 7 that takes 3 lines.

logging.level.org.hibernate.SQL=debug spring.jpa.properties.hibernate.generate_statistics=true logging.level.org.hibernate.session.metrics=debug 

The third line is new. I first ran with only generate_statistics=true, as older guides suggest, and got no metrics at all, because Hibernate 7 logs them at DEBUG on org.hibernate.session.metrics. With that logger on, every session ends with a block like this one, and the line to read is the statement count.

DEBUG org.hibernate.session.metrics : HHH000401: Logging session metrics: 7897416 ns acquiring 1 JDBC connections 3258002 ns preparing 11 JDBC statements 64767081 ns executing 11 JDBC statements ... 

Prefer the logger to spring.jpa.show-sql=true. show-sql writes straight to System.out with a bare Hibernate: prefix, so its lines carry no timestamp or thread, skip your log files and ignore logging.level.

The repository itself runs a single query, so the extra ones come from where entities become a response: a mapper like the one above, or Jackson serialising an entity and calling getBooks().

Fix 1: JOIN FETCH

JOIN FETCH loads the parents and their children in one SQL statement, which fits a JPQL query written for one screen.

public interface AuthorRepository extends JpaRepository<Author, Long> { @Query("select a from Author a left join fetch a.books") List<Author> findAllWithBooks(); } 

Change the service to call repo.findAllWithBooks() and call the endpoint again. The log now has one statement.

org.hibernate.SQL : 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 org.hibernate.session.metrics : HHH000401: Logging session metrics: 1444958 ns preparing 1 JDBC statements 

Older answers add select distinct a against duplicate authors, but since Hibernate 6 duplicate parents are removed for you. Hibernate 7.4 still passes distinct on to PostgreSQL as an extra deduplication step, and without an order by the row order changed between runs.

What happens when you add paging

On Hibernate 6.6, the query below loaded every row and cut the page in memory. Hibernate 7.4 on PostgreSQL handles it better.

@Query(value = "select a from Author a left join fetch a.books", countQuery = "select count(a) from Author a") Page<Author> findPageWithBooks(Pageable pageable); 

Asking for the first page of 5 authors gives 2 statements, and the database cuts the page inside a derived table.

org.hibernate.SQL : 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 offset ? rows fetch first ? rows only) a1_0(id,name) left join book b1_0 on a1_0.id=b1_0.author_id org.hibernate.SQL : select count(a1_0.id) from author a1_0 

Sort.by("name") and @EntityGraph plus Pageable behaved the same. The old behaviour still exists, though. When I ordered by a column of the fetched collection, Hibernate fell back to paging in memory:

WARN org.hibernate.orm.query : HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory DEBUG org.hibernate.SQL : 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 order by b1_0.title desc,a1_0.id 

Warning: when Hibernate cannot push the page into the database, it logs HHH90003004 and runs the query without offset. The response still has the right 5 rows, so nothing looks wrong until the table is large.

A WARN line is easy to miss, so I would make that case fail. With the property below, the fallback query throws JpaSystemException: setFirstResult() or setMaxResults() specified with collection fetch join (in-memory pagination was about to be applied, ...), while the derived-table query above keeps working.

spring.jpa.properties.hibernate.query.fail_on_pagination_over_collection_fetch=true 

Fix 2: @EntityGraph

@EntityGraph gives the same result as JOIN FETCH while you keep a derived query, that is, a method whose query Spring Data builds from its name, such as findByNameContaining.

@EntityGraph(attributePaths = "books") List<Author> findByNameContaining(String keyword); 

Calling findByNameContaining("") returns all 10 authors in one statement.

org.hibernate.SQL : 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 where a1_0.name like ? escape '\' 

It is still a left join, so the paging notes from Fix 1 apply here too.

Fix 3: batch fetching

Batch fetching keeps lazy loading but replaces the N single queries with a few larger ones. The first time you touch books on one author, Hibernate loads the books for up to batch_size authors in the session with one statement. You can turn it on globally:

spring.jpa.properties.hibernate.default_batch_fetch_size=50 

Or only for one association, with @BatchSize:

@OneToMany(mappedBy = "author") @BatchSize(size = 50) // org.hibernate.annotations.BatchSize private List<Book> books = new ArrayList<>(); 

With the plain repo.findAll() from the N+1 version and only the property added, the log shows 2 statements.

org.hibernate.SQL : select a1_0.id,a1_0.name from author a1_0 org.hibernate.SQL : select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id = any (?) 1653000 ns preparing 2 JDBC statements 

Many guides show in (?, ?, ...) here, but on PostgreSQL Hibernate 7 sends the ids as one array parameter, as logging.level.org.hibernate.orm.jdbc.bind=trace shows.

org.hibernate.orm.jdbc.bind : binding parameter (1:ARRAY) <- [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]] 

Batch fetching never touches the page query, so it is safe for paged lists. With repo.findAll(PageRequest.of(0, 5)) the database still cuts the page.

org.hibernate.SQL : select a1_0.id,a1_0.name from author a1_0 offset ? rows fetch first ? rows only org.hibernate.SQL : select count(a1_0.id) from author a1_0 org.hibernate.SQL : select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id = any (?) 

Without batching, the same request runs 7 statements (page, count and 5 book queries) instead of 3.

Fix 4 (Advanced): a two-step query for paged lists

The two-step query does by hand what Hibernate 7.4 did with the derived table. The first query loads the ids of the page with a normal offset, and the second fetches those authors with their books. Use it on Hibernate 6, when Hibernate cannot push the page down, or when you want the page query explicit.

@Query(value = "select a.id from Author a order by a.id", countQuery = "select count(a) from Author a") Page<Long> findAuthorIds(Pageable pageable); @Query("select a from Author a left join fetch a.books where a.id in :ids order by a.id") List<Author> findWithBooksByIdIn(@Param("ids") List<Long> ids); 
public Page<AuthorDto> pageTwoStep(int page, int size) { Page<Long> ids = repo.findAuthorIds(PageRequest.of(page, size)); List<AuthorDto> content = repo.findWithBooksByIdIn(ids.getContent()) .stream().map(AuthorDto::from).toList(); return new PageImpl<>(content, ids.getPageable(), ids.getTotalElements()); } 

With 120 authors in the table, pageTwoStep(2, 20) logs 3 statements and returns 20 authors starting at "Author 41":

org.hibernate.SQL : select a1_0.id from author a1_0 order by a1_0.id offset ? rows fetch first ? rows only org.hibernate.SQL : select count(a1_0.id) from author a1_0 org.hibernate.SQL : select a1_0.id,b1_0.author_id,...,a1_0.name from author a1_0 left join book b1_0 on a1_0.id=b1_0.author_id where a1_0.id in (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) order by a1_0.id 

The fetch query needs its own order by, because in (...) does not keep the order of the ids. On Hibernate 7.4, JOIN FETCH plus Pageable loads the same page in 2 statements, so the two-step query costs one more round trip.

(Advanced) Choosing a batch size: 10, 50 or 100

The 50 above is a starting point, not a tuned value. With 10 authors every size gives 2 statements, so the table uses 120 authors:

Batch size Full list (120) Page of 20 Two-step, page of 20
off 121 22 3
10 13 4 3
50 4 3 3
100 3 3 3

On a page of 20, any size of 20 or more gives 3 statements, while 10 needs 2 book queries (ids 41–50, then 51–60). The size only matters much when you load a whole list. The SQL text never changes, only the array gets longer, and each round trip gets heavier. Batch 100 on the full list pulls 300 book rows in one query.

These are statement counts, not timings, so nothing here shows batch 100 beating batch 50 on the full list.

Which fix to choose

For list endpoints with one collection, like this one, I would turn on batch fetching globally (around 50) as a safety net and add an explicit JOIN FETCH or @EntityGraph for screens you know. For paged lists, check the log for the derived table, and use batch fetching or the two-step query when the page cannot be pushed down. That is a starting point for read-only lists, not a rule for every query.

Fix When to use Main trade-off
JOIN FETCH Unpaged lists; JPQL written for one screen Paging works only when Hibernate can push it into a derived table; 2 List collections fail
@EntityGraph You want to keep a derived query Same limits as JOIN FETCH
Batch fetching Paged lists, or globally as a safety net Still 1 + ceil(N / batch_size) statements; bigger batches mean heavier queries
Two-step query Paged lists where the page cannot be pushed down, or Hibernate 6 More code and one extra round trip; the fetch query needs its own order by

Warning: JOIN FETCH on 2 List collections in one query fails with MultipleBagFetchException: cannot simultaneously fetch multiple bags, which Spring wraps in InvalidDataAccessApiUsageException. The application starts normally and fails only when the method runs, so a test must call it. Change one side to a Set, or fetch one collection and let batch fetching load the other.

A screen that needs only a few columns is often simpler with a DTO projection. FetchType.EAGER is not a fix either. With books set to EAGER, findAll() still ran 11 statements, and every other load of Author drags the books along.

A test that stops N+1 from coming back

N+1 returns quietly, for example when someone adds a lazy field to a DTO. The test below counts SQL statements with Hibernate Statistics and fails when the number goes up. The settings go in src/test/resources/application.properties:

spring.sql.init.mode=always spring.jpa.hibernate.ddl-auto=none spring.jpa.properties.hibernate.generate_statistics=true 

Why not H2? data.sql uses generate_series, and a count is only worth trusting on your production engine. The test starts a real PostgreSQL with Testcontainers (the Testcontainers post covers the setup). Spring Boot 4 moved the JPA test slice into its own module, so here are the full imports:

import static org.assertj.core.api.Assertions.assertThat; import jakarta.persistence.EntityManagerFactory; import org.hibernate.SessionFactory; import org.hibernate.stat.Statistics; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest; import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase; import org.springframework.boot.testcontainers.service.connection.ServiceConnection; import org.springframework.context.annotation.Import; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.postgresql.PostgreSQLContainer; @DataJpaTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) @Testcontainers @Import(AuthorService.class) class AuthorQueryCountTest { @Container @ServiceConnection static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:18-alpine"); @Autowired AuthorService service; @Autowired EntityManagerFactory emf; Statistics stats; @BeforeEach void resetStats() { stats = emf.unwrap(SessionFactory.class).getStatistics(); stats.clear(); } @Test void listAuthors_runsOneQuery() { var authors = service.listAuthors(); assertThat(authors).hasSize(10); assertThat(stats.getPrepareStatementCount()) .as("SQL statements to list authors") .isEqualTo(1); } } 

The test dependencies are spring-boot-starter-data-jpa-test, spring-boot-testcontainers, org.testcontainers:testcontainers-postgresql and org.testcontainers:testcontainers-junit-jupiter, versions managed by Boot. Testcontainers 2 renamed those artifacts, and its PostgreSQLContainer has no type parameter. The Hibernate: select ... lines in the test output come from @DataJpaTest, which turns show-sql on by default.

Running mvn test against the findAll() version fails.

[ERROR] dev.duongvu.nplus1.AuthorQueryCountTest.listAuthors_runsOneQuery -- Time elapsed: 0.096 s <<< FAILURE! org.opentest4j.AssertionFailedError: [SQL statements to list authors] expected: 1L but was: 11L 

After switching listAuthors() to repo.findAllWithBooks(), it passes.

[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS 

The @EntityGraph version passes too. With @BatchSize(size = 50) the test reports expected: 1L but was: 2L, which is the correct count for that fix while authors ≤ batch size, so assert isEqualTo(2) there.

The test can also go green for the wrong reason when the data is still in the persistence context, the entity cache of the current session. When I seeded 10 authors with TestEntityManager.persist() and called the N+1 version right away, the test counted 1 statement, because the books were already in memory. Adding em.clear() before the call brought the count back to 11.

Common mistakes

  • Expecting generate_statistics alone to print metrics on Hibernate 7.
  • Adding Pageable to a collection fetch without checking the log for the derived table or HHH90003004.
  • Asserting statement counts on H2, or with seed data still in the session.

Once the count is right, the cost of each query comes next, covered in PostgreSQL indexes with EXPLAIN ANALYZE, with the wider database side in Databases for app developers. Caching with Redis is a separate topic. The next post in this series covers @Transactional pitfalls, including why the readOnly transaction in AuthorService is what made lazy loading work here.