Lesson 11 of 12 · 10 min · Data access with Spring Data JPA
Lazy versus eager loading and the N+1 query problem
What you will learn
- The difference between lazy and eager fetching
- Why
LazyInitializationExceptionhappens - What the N+1 query problem is and how to detect it
- Fix it with
JOIN FETCH,@EntityGraph, batch fetching and projections - Why
spring.jpa.open-in-viewshould be off
In simple words
Imagine asking for a list of 100 customers, and then, for each one, walking to a different cabinet to fetch their address. That is 101 trips instead of one or two. Hibernate does exactly this by default when you touch a lazy relationship inside a loop, and the page that worked fine with 5 rows crawls with 5,000. Learning to spot and fix this "N+1" pattern is one of the most valuable JPA skills, and a favourite interview topic.
Words to know
- Lazy loading: fetching related data only when you first use it.
- Eager loading: fetching related data immediately with the parent.
- N+1 problem: one query for a list plus one extra query for each item.
- Fetch join: a query that loads a parent and its related objects together.
Lazy and eager
When you load an Order, should Hibernate also load its customer and lines?
- LAZY: no. It puts a proxy or an uninitialised collection in the field, and runs a query only when you first call a method on it.
- EAGER: yes, immediately (by a join or an extra query).
Defaults in JPA:
| Association | Default |
|---|---|
@ManyToOne, @OneToOne |
EAGER |
@OneToMany, @ManyToMany |
LAZY |
Eager defaults are a trap: loading one order loads its customer; loading the customer may load its other eager associations, and so on, and you cannot turn eager off for a particular query. Best practice: make every association LAZY (@ManyToOne(fetch = FetchType.LAZY)) and fetch what each use case needs explicitly in the query.
The N+1 problem
List<Order> orders = orderRepository.findAll(); // 1 query
for (Order o : orders) {
System.out.println(o.getCustomer().getName()); // N more queries, one per order
}
The SQL log shows:
select o.* from orders o; -- 1 query returns 100 orders
select c.* from customers c where c.id = ?; -- repeated up to 100 times
select c.* from customers c where c.id = ?;
...
101 queries instead of 1 or 2. Often invisible with test data and disastrous in production. The same happens with collections (order.getLines().size() inside a loop) and with eager associations loaded by findAll.
How to detect it:
spring.jpa.show-sql=trueorlogging.level.org.hibernate.SQL=DEBUGand count the statements for one request.- Hibernate statistics (
spring.jpa.properties.hibernate.generate_statistics=true) print the number of statements. - In tests, assert the query count with a library such as
datasource-proxyor Hibernate'sStatementInspector, so a regression fails the build. - Observability tools (APM) that show many identical short queries in one trace.
Fix 1: fetch join
Ask for the parent and the association in one query with JOIN FETCH in JPQL:
@Query("select o from Order o join fetch o.customer where o.status = :status")
List<Order> findWithCustomer(@Param("status") OrderStatus status);
One SQL join returns orders with customers. Use left join fetch if the association may be null. Warnings:
- Fetching two collections at once (
join fetch o.lines join fetch o.payments) creates a Cartesian product and Hibernate may throwMultipleBagFetchException. Fetch one collection per query, or use batch fetching. - Paging with a collection fetch join makes Hibernate load everything in memory and paginate there (a warning
HHH90003004: firstResult/maxResults specified with collection fetchappears). Page the parents first, then fetch the children. - Duplicate parents can appear with a collection fetch; Hibernate 6 and 7 de-duplicate entity results automatically.
Fix 2: @EntityGraph
The same without writing JPQL, on a derived query method:
@EntityGraph(attributePaths = {"customer"})
List<Order> findByStatus(OrderStatus status);
@EntityGraph(attributePaths = {"customer", "lines", "lines.product"})
Optional<Order> findDetailedById(Long id);
The attribute paths are loaded eagerly for that method only; the mapping stays lazy. This is the cleanest approach for Spring Data repositories.
Fix 3: batch fetching
When you cannot fetch-join, tell Hibernate to load lazy associations in batches rather than one at a time:
spring.jpa.properties.hibernate.default_batch_fetch_size=50
(or @BatchSize(size = 50) on an association). Now touching the customers of 100 orders runs about 2 queries (where id in (?, ?, ... 50 ids)) instead of 100. It does not remove the extra queries but cuts them dramatically, and it works with pagination, making it a good default for the whole application.
Fix 4: projections and DTOs
If you only need a few columns for a list screen, do not load entities at all:
@Query("select new com.shop.orders.OrderRow(o.id, o.amount, c.name) from Order o join o.customer c")
List<OrderRow> rows();
One query, no entities, no lazy loading, no N+1. For read-heavy endpoints this is usually the best answer. Also consider a read-only reporting query in SQL.
Open Session in View
By default Spring Boot sets spring.jpa.open-in-view=true: the JPA session stays open until the web response is written, so lazy loading works in controllers and during JSON serialisation, and hides N+1 problems and LazyInitializationException, while holding a database connection for the whole request (including slow rendering and serialisation). Spring Boot logs a warning at startup. Set it to false and fetch explicitly in the service layer:
spring.jpa.open-in-view=false
Then lazy loading outside a transaction fails loudly during development, which forces you to write the right query and return DTOs.
Choosing the fix
| Situation | Use |
|---|---|
| a list screen needing a few columns | projection or DTO query |
| one entity with a few associations | @EntityGraph or join fetch |
| a paged list that touches associations | page parents, then default_batch_fetch_size or a second fetch |
| many places that lazily navigate | hibernate.default_batch_fetch_size as a safety net |
| a huge export | stream results or native SQL, with a read-only transaction |
Also remember
size()on a lazy collection loads it all; use acountquery when you only need the number.getReferenceByIdcreates a proxy without a query: perfect for setting a foreign key (order.setCustomer(customers.getReferenceById(id))).- Read-only transactions (
@Transactional(readOnly = true)) let Hibernate skip dirty checking and flush work, helping read paths. - Second-level caches and query caches exist but add complexity; fix the queries first.
- Test with realistic data volume: N+1 is invisible with 3 rows.
Common mistakes
- Eager fetching on associations to "fix" lazy errors.
- Leaving
open-in-viewon and shipping N+1 into production. - Looping over entities and navigating associations without a fetch plan.
- Fetch-joining several collections or paging with one.
- Returning entities from the API, which triggers lazy loads in serialisation.
- Never looking at the SQL log.
Try it yourself
- Create 100 orders for 20 customers, call
findAll(), printo.getCustomer().getName()in a loop, and count the SQL statements. - Fix it with
join fetch, then with@EntityGraph, and compare the count. - Set
default_batch_fetch_size=20on the original code and see the change. - Set
open-in-view=falseand provoke aLazyInitializationException; then fix it properly. - Write a test that fails if loading the order list runs more than 2 queries.
Check yourself
What are the default fetch types for @ManyToOne and @OneToMany?
@ManyToOne and @OneToOne default to EAGER; @OneToMany and @ManyToMany default to LAZY.
What causes LazyInitializationException?
Accessing a lazy association after the persistence session or transaction has closed, so Hibernate cannot load it.
What is the N+1 query problem?
One query loads N parent rows, and then touching a lazy association for each parent triggers N additional queries.
Why disable spring.jpa.open-in-view?
It keeps a database connection open for the whole request and hides lazy-loading and N+1 problems; turning it off forces explicit fetching in the service layer.
Interview questions
How do you solve the N+1 problem in JPA?
Fetch the association in the same query with JOIN FETCH or @EntityGraph, use batch fetching (default_batch_fetch_size or @BatchSize), or avoid entities with a DTO or projection query; detect it first by counting SQL statements.
What is the difference between JOIN FETCH and a normal JOIN in JPQL?
A normal join only uses the joined table for filtering or selecting; JOIN FETCH also initialises the association on the returned entities, so no extra query is needed to access it.
Why is FetchType.EAGER considered a bad default?
It always loads the association even when not needed, cannot be switched off per query, and cascades into many extra queries or joins; lazy mappings plus explicit fetching are more predictable.
Summary
- Make all associations lazy and fetch what each use case needs explicitly.
- N+1 appears when you navigate a lazy association in a loop; detect it by counting SQL statements.
- Fix with
JOIN FETCH,@EntityGraph, batch fetching or DTO projections. - Turn
open-in-viewoff, and test with realistic data volume.
Going deeper
- Spring Data JPA: Entity graphs:
@EntityGraphon repository methods. - Spring Boot: Open EntityManager in View: the default and the warning.
- Hibernate documentation: current user guides and versions.
See how much of this you can explain
A free mock interview asks you new questions on Spring Boot, REST and JPA for Java Full Stack Developer and scores every answer, with what to fix.