What you'll learn: By the end of this lesson you will be able to explain why a lazily loaded association turns one query into N+1, count the statements a piece of JPA code really sends, fix the problem with a join fetch or with batch fetching and say what each fix costs, avoid the pagination and
LazyInitializationExceptiontraps that come with them, and read the lab's captured statement counts to confirm it.
Picture a clerk asked for twelve customer orders and their order lines. One clerk fetches the list of twelve orders, then walks to the archive once for each order to bring back its lines: thirteen trips. Another asks the archive for all the lines of all twelve orders in one request, or in a few big batches. The paperwork is identical; the trips are not. On a desk next to the archive the walking is invisible. Over a network, each trip is a database round trip.
That is the N+1 select problem, and in JPA it is not a bug in your code, it is what a lazy association does when you loop over it. This lesson builds on Spring @Transactional, because lazy loading only works while a session (a persistence context) is open, and a transaction is usually what keeps it open.
Verified with Spring Boot 4.1.2, Hibernate ORM 7.4.13.Final, Java 25, H2 2.4.240 and the Hibernate and Spring documentation, on 2026-12-01.
The core idea
With a lazy association, Hibernate loads the parent rows with one query and then runs one more query the first time each parent's children are touched. For N parents that is N+1 statements. The fixes change when and how the children are loaded: in the same query (join fetch), in a few queries of many parents each (batch fetching), or only for the parents you actually page through.
Three illustrations run through it:
- Minimal example: 12 orders with 3 lines each, loaded five ways in the lab.
- Realistic example: ShopStream's order history page, in "In practice".
- Failure example: a lazy list touched after the session closed, and a lazy field touched by a serializer.
Lazy loading, and why it exists
Loading an order should not drag in every line, product and shopper it refers to, so JPA lets an association be lazy: Hibernate puts a placeholder (a proxy or an uninitialised collection) where the data would be and loads it on first access. The defaults differ by association. The Jakarta Persistence Javadoc gives @ManyToOne a default of EAGER, and the Hibernate introduction says that is "not the default for @ManyToOne associations, and must be specified explicitly" when you want lazy, and recommends that all associations be fetch=LAZY. The same text names the cost: the placeholder only works while the session is open, and afterwards its methods throw LazyInitializationException; used in a loop, lazy fetching "almost inevitably leads to the infamous N+1 selects problem".
Figure 1. The lab's model. How to read this: one order owns many lines. CustomerOrder.lines is a @OneToMany list (lazy in JPA), and OrderLine.order is @ManyToOne(fetch = LAZY), set explicitly because the default is eager.
The mapping, from the lab:
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
private List<OrderLine> lines = new ArrayList<>();
The N+1 shape
Here is the loop that causes it, in the lab's service. Nothing in it looks like a query inside a loop:
@Transactional(readOnly = true)
public Report allOrdersLazy() {
return summarise(orders.findAll());
}
private static Report summarise(List<CustomerOrder> loaded) {
int lines = 0;
int quantity = 0;
for (CustomerOrder order : loaded) {
for (OrderLine line : order.getLines()) {
lines++;
quantity += line.getQuantity();
}
}
return new Report(loaded.size(), lines, quantity);
}
Figure 2. One query, then one per parent. How to read this: the first statement is the "1", the repeated line queries are the "N". The count grows with the number of orders, not with the amount of data you need.
Fix 1: join fetch
A join fetch in the query asks for the children in the same statement:
@Query("select o from CustomerOrder o join fetch o.lines order by o.id")
List<CustomerOrder> findAllWithLines();
The Hibernate guide calls join fetching "clearly more efficient than either batch or subselect fetching" and says you should "almost always use outer join fetching". Four things to know. A plain join fetch is an inner join, so a parent with no children drops out of the result (left join fetch keeps it). As of Hibernate 6 the duplicate parent rows that a collection join produces are removed automatically, so distinct is not needed for that. Fetching several collections in parallel produces a Cartesian product at the database level. And restricting a fetch-joined collection in the where clause leaves the collection incomplete.
Pagination. The Hibernate query language guide says "prior to Hibernate 7.4, limits didn't play well with many-valued fetch joins", that this is now fixed on any database that supports limits and offsets in subqueries, and that on a database without that support Hibernate fetches all matching rows and applies the limit in memory, which performs poorly. Row 5 of the lab shows the fixed behaviour on H2: the limit sits in a subquery on the parents. If you run an older Hibernate, or a database without that support, page the parents first and fetch their children separately (row 6).
Fix 2: batch fetching
Batch fetching keeps the lazy design but loads many parents' children per query. Hibernate's hibernate.default_batch_fetch_size takes "a sensible batch size >1"; @BatchSize sets it per entity or collection; and since Hibernate 6.3 a session can override the factory default with Session.setFetchBatchSize, which the lab uses. The guide's own verdict: batching "might mitigate problems involving N+1 selects, but it won't solve them", and it is off by default.
Figure 3. Batch fetching with a size of 5. How to read this: touching one order's lines loads its neighbours' lines too, so the 12 line queries become 3. Which parents share a batch is Hibernate's choice, so the figure shows the shape, not exact ids.
Counting statements
Do not guess, count. Setting hibernate.generate_statistics to true enables Hibernate's statistics, and Statistics.getPrepareStatementCount() is "the number of prepared statements that were acquired"; getCollectionFetchCount() and getEntityLoadCount() count lazy collection loads and loaded entities. In Spring Boot the property goes under spring.jpa.properties.. A test that clears the statistics, runs a use case and asserts a statement count is the cheapest guard against a new N+1.
Build it: the same report loaded five ways
This is the minimal example you can run. The database is H2, in memory, created by Hibernate; no PostgreSQL and no Docker are involved.
Goal. Load 12 orders with 3 lines each (illustrative data) and total the quantities, and compare the SQL that each loading strategy sends.
Setup. From the repository's examples/spring-labs folder:
./gradlew :labs:jpa-n-plus-1:test
It runs 7 tests and a golden-file comparison. The code is in examples/spring-labs/labs/jpa-n-plus-1/src/main/java/buildingai/labs/jpa/.
How it works. OrderReportService has one method per strategy. Each returns the same Report (12 orders, 36 lines, quantity 90, or the page's share), and the test harness clears the statistics, runs the method inside its own transaction and prints the counters and the SQL, grouped with a count, from the org.hibernate.SQL logger. In-lists are shortened to "(5 params)" for readability.
Expected output, captured from a real run (Hibernate 7.4.13.Final, H2 2.4.240, 2026-12-01):
Hibernate on H2 (in-memory): 12 orders, 3 lines each. 'statements' is Hibernate's prepared-statement count for the run.
1 lazy loop (N+1) statements=13 collectionFetches=12 entityLoads=48 Report[orders=12, lines=36, quantity=90]
1 x select co1_0.id,co1_0.shopper from customer_order co1_0
12 x select l1_0.order_id,l1_0.id,l1_0.quantity,l1_0.sku from order_line l1_0 where l1_0.order_id=?
2 batch fetch size 5 statements=4 collectionFetches=3 entityLoads=48 Report[orders=12, lines=36, quantity=90]
1 x select co1_0.id,co1_0.shopper from customer_order co1_0
3 x select l1_0.order_id,l1_0.id,l1_0.quantity,l1_0.sku from order_line l1_0 where l1_0.order_id in (5 params)
3 batch fetch size 20 statements=2 collectionFetches=1 entityLoads=48 Report[orders=12, lines=36, quantity=90]
1 x select co1_0.id,co1_0.shopper from customer_order co1_0
1 x select l1_0.order_id,l1_0.id,l1_0.quantity,l1_0.sku from order_line l1_0 where l1_0.order_id in (20 params)
4 join fetch statements=1 collectionFetches=0 entityLoads=48 Report[orders=12, lines=36, quantity=90]
1 x select co1_0.id,l1_0.order_id,l1_0.id,l1_0.quantity,l1_0.sku,co1_0.shopper from customer_order co1_0 join order_line l1_0 on co1_0.id=l1_0.order_id order by co1_0.id
5 page of 4, join fetch statements=1 collectionFetches=0 entityLoads=16 Report[orders=4, lines=12, quantity=30]
1 x select co1_0.id,l1_0.order_id,l1_0.id,l1_0.quantity,l1_0.sku,co1_0.shopper from (select co1_0.id,co1_0.shopper from customer_order co1_0 where exists(select 1 from order_line l1_0 where co1_0.id=l1_0.order_id) order by co1_0.id offset ? rows fetch first ? rows only) co1_0(id,shopper) join order_line l1_0 on co1_0.id=l1_0.order_id order by co1_0.id
6 page of 4, then batch of 5 statements=2 collectionFetches=1 entityLoads=16 Report[orders=4, lines=12, quantity=30]
1 x select co1_0.id,co1_0.shopper from customer_order co1_0 order by co1_0.id fetch first ? rows only
1 x select l1_0.order_id,l1_0.id,l1_0.quantity,l1_0.sku from order_line l1_0 where l1_0.order_id in (5 params)
7 lines read outside a transaction -> LazyInitializationException
| Row | What it shows |
|---|---|
| 1 | The lazy loop: 13 statements, 12 of them one per order. |
| 2, 3 | Batch size 5 gives 4 statements, size 20 gives 2. In row 2 the last batch holds two orders but all three line queries have five placeholders; in row 3 one query carries 20 placeholders for 12 orders. |
| 4 | Join fetch: 1 statement, the same totals. |
| 5 | A page of 4 with a join fetch: 1 statement, the limit in a subquery, only 16 entities loaded. |
| 6 | The parents page first (limit, no join), then one batched query for their lines: 2 statements, the same 16 entities. |
| 7 | Touching the lines with no open session fails with LazyInitializationException. |
What differs on PostgreSQL. Statement counts are decided by Hibernate before SQL reaches the database, so the N+1 shape and the join fetch count should match. This lab cannot show what a real PostgreSQL changes: the SQL text and dialect (the paging syntax and how the in-list is written), how a batch loader groups and pads ids, the query plan, and above all the time, because H2 in memory makes a round trip nearly free. Measure on the real database before you decide that a count is small enough.
Break it. Remove join fetch from findAllWithLines: the join-fetch test fails with 13 statements instead of 1. Restore it and re-run.
Stretch. Add an @EntityGraph variant, subselect fetching, and a product association on OrderLine to see N+1 compounding (N orders times M lines).
What the lab leaves out. Write batching, the second-level cache, other databases, concurrency and any timing.
The other batching: writes
Fetch batching is not the only batching. hibernate.jdbc.batch_size is the "maximum batch size for SQL statement batching", which the Hibernate guide says helps when a transaction runs many DML statements against the same table. The lab does not measure it, so this lesson makes no claim about its effect or about which id generators allow it; check the settings page for your version and count executions on your database.
Choosing a fix
Figure 4. Pick the fix per use case. How to read this: the right fix depends on whether the children are always needed and whether the list is paged, so it is a property of the query, not of the whole application.
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
| Lazy loop | Simple code | N+1 statements | The list is more than a handful of rows |
| Join fetch | One statement | Wider rows, duplicates removed in memory, one collection per query, paging needs care | You page on a Hibernate or database without in-query limits |
| Batch fetching | Few statements, no query changes, lazy stays lazy | Still more than one extra statement, padded in-lists, batch choice is Hibernate's | You need exactly one statement |
| Page then batch | Loads only the page and its children | Two statements | The page is tiny and a join fetch is simpler |
In practice: ShopStream's order history page
This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company. The 20 orders per page are illustrative.
This is a realistic scenario, not a case history.
The situation
The shopper's order history page lists the 20 most recent orders and, for each, its lines. The team wants the page to cost a small, fixed number of database statements however many lines an order has.
Starting architecture
Figure 5. The path the count is measured on. How to read this: the number on the last arrow is what the lab changes. Before the fix it grows with the page size; afterwards it is fixed.
Options considered
| Option | Statements for a page of 20 orders | Risk |
|---|---|---|
| A. Lazy loop | 1 + 20 (the lab's row 1, scaled) | Grows with the page, and with every new association touched |
| B. Join fetch with the page | 1 | Depends on the Hibernate version and database applying the limit in the query |
| C. Page the orders, then batch fetch lines | 2 expected (row 6 scaled up, with a batch size of at least 20) | Batch padding and grouping are Hibernate's |
The decision
Option C for the history page, because it does not depend on how the database handles a limit over a join, with a statement-count test that fails above 2. A modest default_batch_fetch_size is set as a safety net for other lazy reads, and join fetch is kept for the few use cases that always need the children and never page.
Rollout and verification
Port the lab's statistics harness into the service's tests: seed 20 orders with several lines, clear the statistics, call the use case, assert the statement count and the totals. In production, log SQL for a sampled request or compare statement counts per request in the service's metrics, and check on the real database, not only H2, that the page is as fast as the count suggests.
The 2 a.m. failure
The page reads: the order history endpoint has become slow after a release that added each product's name to the response. The serializer calls line.getProduct().getName(), a lazy association nobody fetched, so each line now triggers its own query during JSON rendering. It worked in the new tests because those ran inside a transaction.
Checks: log the SQL for one request (the org.hibernate.SQL logger at debug, as the lab does) and count statements per request; look for lazy access from serializers or templates. Spring Boot registers OpenEntityManagerInViewInterceptor by default in a web application, which keeps the session open through the view and lets lazy loading work there; that hides the problem instead of raising LazyInitializationException. The mitigation is to fetch the product with the lines (join fetch or batch). The lasting fix is the statement-count test, and a decision on whether to set spring.jpa.open-in-view to false, which turns the hidden query into an immediate, visible failure.
Architect's notes
- Measure statements per use case. Counts are cheap to assert and catch regressions.
- Make associations lazy and fetch per query. Eager mappings fix one query and break every other.
- Do not let the view layer load data. Fetch what a response needs before it leaves the transaction.
- Prefer a decision per list. Join fetch for always-needed children, page-then-batch for paged lists.
- Check the version. The pagination behaviour of a collection join changed in Hibernate 7.4.
- Check the real database. Counts transfer to PostgreSQL; times and SQL text do not.
Common mistakes
- Making everything eager to silence the exception. It trades one failure for loading too much everywhere.
- Trusting
distinctor in-memory dedup to fix row explosion. Dedup hides duplicates, not the wide result set. - Join fetching two collections in one query. That produces a Cartesian product.
- Paging a collection join without checking the Hibernate version and database.
- Treating batch size as a cure. It reduces N+1, it does not remove it.
- Judging speed on an in-memory database. Round trips are free there.
Key takeaways
- A lazy association touched in a loop sends 1 + N statements.
- Join fetch makes it one statement; batch fetching makes it about N divided by the batch size, plus one.
- Count statements with Hibernate's statistics instead of guessing.
- Pagination with a collection join depends on the Hibernate version and the database; page the parents and batch the children when in doubt.
- Lazy loading needs an open session; hiding that with open-in-view moves the cost, it does not remove it.
- Counts carry over to PostgreSQL; timing and SQL text must be measured there.
Practice exercises
Exercise 1 (20 min). For 12 orders, compute the statements for a batch size of 4, 5 and 12, then run the lab with each and compare.
Exercise 2 (45 min). Add a lazy Product association to OrderLine, load the 12 orders with a join fetch of lines only, and predict the statement count before running it.
Exercise 3 (1 hour). Run "Break it". Then copy findAllWithLines to a second method with the same query text and a Pageable, run both in one process in either order, and describe what you observe.
Exercise 4 (2 hours). For ShopStream's order history, cart and product list, choose join fetch, page-then-batch or lazy-with-batch for each, write the statement count you expect for a page of 20 and add a test that asserts it.
Related reading
- Spring @Transactional: the session and transaction that lazy loading depends on.
- Databases Basics: rows, tables, joins and where an ORM sits.
- ShopStream Data Model: the relational core behind orders and lines.
Official documentation
- Hibernate ORM: Introduction to Hibernate 7 (proxies and lazy fetching, association fetching, batch fetching, statistics).
- Hibernate ORM: Query language guide (join fetch, duplicate removal, limits and offsets).
- Hibernate Javadoc: Session, Statistics and BatchSize.
- Jakarta Persistence Javadoc: ManyToOne and OneToMany.
- Spring Boot reference: Working with SQL databases (Open EntityManager in View).