Find and Fix Hibernate’s N+1 Problem with a Reproducible Test

The endpoint returned 200 OK. It also ran 21 SQL queries.

The library’s new GET /books endpoint returned twenty books in order, each with the right publisher name. The library client got exactly what it asked for. Underneath that small JSON response, Hibernate first read the books, then looked up each publisher separately. The response could pass a functional test while the database work grew with the list.

In the Java series we counted physical copies of The Night Library and imported inventory scans. Here the same title appears in a fictional catalog of titles with publisher information. The catalog is a separate example with twenty books and twenty different publishers. Java collections and the library inventory · Java exceptions and the inventory import

Follow the SQL from one request

JPA lets this application query persistent Java objects, called entities. Hibernate implements JPA and translates those queries and entity loads into SQL. A Book row carries a publisher_id foreign key. Its Java object has a Publisher association with fetch = FetchType.LAZY, so the initial query can load the books while deferring publisher details.

One GET /books request runs 21 SQL queries for 20 books. One query reads the books and 20 look up their separate publishers. The DTO projection runs one joined query and returns the same JSON.
One book query followed by twenty publisher lookups becomes one joined query.

The capture shows where the extra statements come from.

  1. The entity query issues one SELECT from books, ordered by ID and limited to twenty results. Each row gives Hibernate the ID of the associated publisher.
  2. The service maps each managed Book into a BookView while its read-only transaction is open. BookView is a data transfer object (DTO) with the fields the endpoint returns. Calling book.getPublisher().getName() needs the name. Hibernate initializes that lazy reference with a publisher SELECT. The first publisher lookup binds ID 101.
  3. The second and third books repeat that SQL shape with IDs 102 and 103. The remaining books do the same, through publisher 120. That yields one book query plus twenty publisher queries. The question marks are prepared statement placeholders. Their recorded bind values show which rows were requested. Hibernate ORM 7.4 fetching guide
SQL captured at JDBC for the two default GET /books requests. Whitespace was adjusted for reading. The same publisher SQL repeats with distinct IDs.

The count depends on which publisher entities Hibernate still needs to load. In this application each read starts with a fresh transaction-scoped persistence context, the set of entities Hibernate manages for that transaction. The first-level cache in that context can reuse a loaded publisher if several books share it. The fixture gives each book a different publisher. The second-level entity cache and query cache are disabled, the default batch fetch size is zero, and there is no association-level batch override. Open EntityManager in View is off. The mapper loads the publisher before the service returns, and the controller serializes plain DTOs. Hibernate ORM 7.4 persistence context and fetching

The code that fans out

@Transactional(readOnly = true)
public List<BookView> listLazy(int limit) {
    return entityManager.createQuery("select b from Book b order by b.id", Book.class)
            .setMaxResults(limit)
            .getResultList()
            .stream()
            .map(book -> new BookView(
                    book.getId(), book.getTitle(), book.getPublisher().getName()))
            .toList();
}

The initial JPQL query selects Book entities. JPQL refers to Java entities and their attributes. The call to getName() inside the stream is where each unloaded publisher becomes needed.

See the same request in BootUI

BootUI 2.6.0 is an optional browser view of the lab. Its release advances its Spring baseline to Boot 4.2.0, the version used here. Open Live Activity on the local BootUI dashboard, send a fresh GET /books, and open that request. The SQL & cache tab groups statements with the same SQL shape. Check the correlation label in the SQL section. BootUI 2.6.0 release notes · BootUI 2.6.0 request profiler

In the local lazy run, the profile showed 21 SQL statements and flagged a group of twenty identical publisher lookups. The projection run showed one statement with the join. BootUI marked the SQL in both profiles as exact by request ID. The Maven test uses its own JDBC listener, so its assertions run without the dashboard.

Ask the database for the three fields the page needs

This endpoint returns id, title and publisherName. It only reads data, so a constructor projection is a direct fit. The query joins each book to its required publisher and constructs the same BookView record from three values. The join is an inner join because each book must have a valid publisher. Both reads limit the results and sort by b.id. Hibernate ORM 7.4 query language guide

@Transactional(readOnly = true)
public List<BookView> listProjected(int limit) {
    return entityManager.createQuery("""
            select new com.homannsoftware.library.BookView(b.id, b.title, p.name)
            from Book b join b.publisher p
            order by b.id
            """, BookView.class)
            .setMaxResults(limit)
            .getResultList();
}

The resulting SQL reads the three output columns in one joined query. JPA constructs the records directly. There are no managed publisher references for the mapper to initialize. Here is the full response for GET /books?limit=1 in either mode, formatted for reading.

[
  {"id": 1, "title": "The Night Library", "publisherName": "Publisher 01"}
]

When you still need entities

  • A fetch join such as select b from Book b join fetch b.publisher order by b.id loads both entities for this to-one association. Use it when the application needs managed Book objects and their publishers.
  • A JPA Entity Graph lets a query declare that it needs publisher while keeping the fetch plan separate from the query text. Inspect the generated SQL if a particular statement budget matters.
  • Batch fetching groups several unloaded publishers into a secondary query. It can reduce the number of lookups when the code still navigates lazy relationships. The number of statements can still vary with result size and what is already loaded. Hibernate ORM 7.4 fetching strategies

Changing the association to EAGER globally requires publishers to be available at load completion. Hibernate may still use secondary selects for an entity query without a fetch join. The mapping also applies to other reads, including ones that only need book fields. Hibernate ORM 7.4 direct fetching versus entity queries

A collection fetch join deserves a separate check when you page the results. A single book with several children can produce several joined rows, so a limit on joined rows and a limit on books are different operations. Hibernate 7.4 can apply the parent limit with a subquery on dialects that support limits there. Where the database lacks that capability, Hibernate can retrieve the matching rows and apply the limit in memory. Inspect the SQL and page boundaries on your target dialect. Paging parent IDs first and fetching their children in a second query is another option when you need explicit control. Hibernate ORM 7.4 on limits and collection fetch joins

Put a statement budget in an HTTP test

The lab’s test starts two embedded Spring MVC servers with identical H2 data and sends the same HTTP request to each. The mode is chosen at startup, so the client calls the normal GET /books route in both cases. It checks status 200 and compares both complete response bodies with the expected JSON text. That checks the fields, the publisher values, and the order of the books.

The test starts capturing when the servlet filter sees a registered request token. A test-only DataSource proxy records JDBC query executions on that request’s thread. The filter closes the capture in finally, and the test waits for that snapshot after reading the response. Schema creation, seeding and other requests run outside that scope. This approach fits this synchronous endpoint. For an endpoint that hands database work to other threads, propagate the capture context and wait for that work to complete. DataSource-Proxy execution listeners

BooksLazy mappingDTO projection
121
341
561
20211

These are the two count assertions in the test. The next assertions also verify the repeated publisher statement and its bind values on the lazy path and the join on the projection path.

assertThat(before.statements()).hasSize(size + 1);
assertThat(after.statements()).hasSize(1);

For an endpoint with this query shape, the second assertion is a regression budget. If someone reintroduces per-book database calls and the response stays correct, the test still fails. Use a fixture with distinct related IDs and several result sizes so repeated references in the persistence context cannot hide the growth.

The measured change for twenty books is 21 JDBC statements down to 1, for identical JSON. A statement count tells you how much work the application sends as separate SQL statements. To estimate response-time impact, measure separately with your database, data volume, network path and concurrent traffic.

Run it locally

Download the Hibernate N+1 lab (ZIP)

Extract the ZIP, open a terminal beside pom.xml, and run the test. You need JDK 21 and Maven. Maven fetches dependencies on the first build. The application and database run locally.

mvn verify

Run the two modes in separate terminals. The default port serves the lazy version. The second process serves the projection on port 8081.

mvn spring-boot:run
mvn spring-boot:run "-Dspring-boot.run.arguments=--server.port=8081 --library.read-mode=projection"

Call http://127.0.0.1:8080/books and http://127.0.0.1:8081/books with a browser or curl. Add ?limit=3 to try a smaller response. The lab README contains the test commands and the optional visual setup. The verified build used Java 21.0.11, Maven 3.9.11, Spring Boot 4.2.0, Hibernate ORM 7.4.15.Final and H2 2.5.252. Spring Boot 4.2.0 release · Hibernate ORM 7.4.15.Final release · Hibernate ORM 7.4 documentation