Path 5 · lesson 5 of 5
LazyInitializationException in production only
A lazy collection can only load while its session is open. Spring Boot keeps one open for every web request by default, which hides the problem until the same code runs anywhere else.
What you will learn
- Explain what a lazy association is and what it needs in order to load
- Say what
spring.jpa.open-in-viewdoes and why its default hides this exception in web requests - Give four reasons the same code works in development and fails in production
- Repair the read with a join fetch, an entity graph or a DTO, and say what each costs
- Recognise two popular repairs that trade the exception for a performance problem
Before you start
The concept
When Hibernate loads an order, it does not load the order's lines with it. It puts a placeholder where the collection should be and fetches the rows the first time code touches them. That is a lazy association, and it is the default for every collection.
The placeholder can only fetch while the session that loaded the order is still open. With Spring, the session normally lives as long as the transaction. Once the @Transactional method returns, the order is detached: a plain object whose unloaded parts can never be loaded. Touching one throws LazyInitializationException.
So the exception is about timing. The code asked for data after the only moment at which the data could be fetched.
Why it exists
This is the standard "works on my machine" failure of JPA code, because whether it fails depends on where the code runs and not on what the code says. The same line reads a collection successfully in a controller and throws in a scheduled job.
- Production switches the default off. Many teams set
spring.jpa.open-in-view=falsein production configuration, for the reasons below, and leave development on the default. - Production calls the code from elsewhere. A message listener, a scheduled job or an
@Asyncmethod has no web request and so no open session, whatever the setting. - Tests keep the session open. A test annotated with
@Transactionalruns entirely inside one transaction, so every lazy read works. - Production has a cache. An entity returned from a cache was loaded by an earlier request. Its session is long closed.
How it works inside
The lab stores one order with three lines. OrderService.find is @Transactional(readOnly = true) and returns the entity without touching its lines. The caller then asks for order.getLines().size(). The first run uses the default setting.
Program outputjava -jar target/spring-production-lab-1.0.jar --demo=lazy (open-in-view at its default)
Real JVM outputspring.jpa.open-in-view = true 1. HTTP request: the controller reads order.getLines() after the service returned GET /orders/1/lines -> 200 order 1 has 3 lines 2. Background thread (@Async): the same read, no web request org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: lab.PurchaseOrder.lines: could not initialize proxy - no Session 3. The repairs, called with no session open afterwards join fetch: lines = 3, SQL statements = 1 @EntityGraph: lines = 3, SQL statements = 1 DTO in the tx: lines = 3, SQL statements = 2
Program outputThe same, with --spring.jpa.open-in-view=false
Real JVM outputspring.jpa.open-in-view = false
1. HTTP request: the controller reads order.getLines() after the service returned
...
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: lab.PurchaseOrder.lines: could not initialize proxy - no Session
...
GET /orders/1/lines -> 500 {"status":500,"error":"Internal Server Error","path":"/orders/1/lines"}
2. Background thread (@Async): the same read, no web request
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: lab.PurchaseOrder.lines: could not initialize proxy - no SessionSpring Boot does tell you about the default. Every start of a web application that has not set the property logs this warning, taken from the first run:
Program outputFirst line of the first run
Real JVM output2026-11-28T12:28:47.461Z WARN 33053 --- [spring-production-lab] [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
| Repair | SQL statements in the lab | What it does |
|---|---|---|
join fetch in the query | 1 | Loads the order and its lines in one statement with a join |
@EntityGraph(attributePaths = "lines") | 1 | The same join, declared on the repository method instead of in the query text |
| Build a DTO inside the transaction | 2 | Reads the order, then the lines, while the session is open, and returns plain data |
Architecture
Drawing diagram…
A flowchart. Inside a web request, a controller calls a transactional service method, which calls a repository, which reads the database. When the transaction ends the session closes, unless open-in-view keeps it, and the order becomes detached with its lines not loaded. The detached order goes back to the controller, where reading the lines works only while a session is open, and to a scheduled job, listener or async thread, where reading the lines throws LazyInitializationException.
flowchart LR
subgraph REQ["Web request"]
C["Controller"] --> S["Service method, @Transactional"]
S --> R["Repository"]
end
R --> DB[("Database")]
S -. "transaction ends: session closes, unless open-in-view keeps it" .-> D["Detached order, lines not loaded"]
D --> C
D --> J["Scheduled job, listener or @Async thread"]
C -. "getLines(): works only while a session is open" .-> DB
J -. "getLines(): no session, exception" .-> X["LazyInitializationException"]- The service method is the natural boundary: everything the caller will need has to be loaded before it returns.
- Open-in-view moves that boundary out to the end of the request, but only for requests. Threads that do not serve a request never had it.
Step by step
Drawing diagram…
A sequence diagram. A nightly export job calls find on the order service. The service opens a session and a transaction, Hibernate selects the order, and the order is returned with its lines not loaded. The transaction ends and the session closes. The job then calls getLines and size on the order and gets LazyInitializationException, no Session.
sequenceDiagram
participant J as Nightly export job
participant S as OrderService
participant H as Hibernate session
participant DB as Database
J->>S: find(orderId)
S->>H: open session, begin transaction
H->>DB: select the order
DB-->>H: one row
S-->>J: order, lines not loaded
Note over H: transaction ends, session closed
J->>J: order.getLines().size()
Note over J: LazyInitializationException: no Session- Only one query was sent, for the order. The lines were never asked for while it was possible.
- The stack trace points at the line that touched the collection, in the job. The fix belongs in the service or the repository, where the data should have been loaded.
In a real system
Open-in-view is convenient and has a price, which is why teams turn it off. With it, lazy loads happen in controllers and while the response is being written, outside the service's transaction. Each one is a separate query that nobody planned, and a list of 50 orders rendered with their lines becomes 51 queries without any exception to point at it.
- Decide what a method returns. A service that returns entities hands its callers a trap. A service that returns DTOs has loaded everything by definition.
- Fetch per use case. The order list needs no lines; the order page needs them. Two repository methods with different fetching are better than one mapping that tries to suit both.
- A join fetch on a collection breaks paging. Hibernate then pages in memory after loading every row, and logs a warning. Page the ids first, then fetch by id.
Connection pool exhaustion
Simulation, not a real clusterUnplanned queries per request are one of the ways a connection pool runs dry under load.
Step 1 · The pattern
Borrow a connection, give it back
The app keeps a small pool of open database connections. Each request borrows one, runs its query and returns it. Fast queries mean a connection is free almost immediately.
- request
- served
Java and Spring Boot
The repository and service from the lab, labs/jvm/spring-production/src/main/java/lab, with the three repairs side by side.
interface OrderRepository extends JpaRepository<PurchaseOrder, Long> { @Query("select o from PurchaseOrder o join fetch o.lines where o.id = :id") Optional<PurchaseOrder> findWithLinesJoinFetch(Long id); @EntityGraph(attributePaths = "lines") Optional<PurchaseOrder> findWithLinesById(Long id);}Why it is written this way
- Both methods produce one SQL statement that joins the order to its lines. The collection is loaded when the method returns.
- The plain
findByIdstays available for callers that do not need the lines, so the join is only paid where it is used.
record OrderSummary(Long id, String customer, int lineCount) {}@Serviceclass OrderService { private final OrderRepository orders; OrderService(OrderRepository orders) { this.orders = orders; } @Transactional(readOnly = true) public OrderSummary summary(Long id) { PurchaseOrder o = orders.findById(id).orElseThrow(); return new OrderSummary(o.getId(), o.getCustomer(), o.getLines().size()); }}Why it is written this way
- The lazy read happens inside the transaction, where it is allowed. It costs a second statement, which the lab counted.
- The caller receives a record. There is nothing lazy left in it, so it is safe on any thread, in a cache and in a JSON serialiser.
Wrong, then right
A nightly job exports orders with their lines. The incorrect version makes the exception go away. The corrected version loads the data.
Incorrect implementation
@Entityclass PurchaseOrder { @OneToMany(mappedBy = "order", fetch = FetchType.EAGER) // "fixes" the job List<OrderLine> lines;}// or, in application.properties:// spring.jpa.properties.hibernate.enable_lazy_load_no_trans=trueWhy it is written this way
- Both changes are one line, and both make the exception disappear everywhere at once.
Why it fails
FetchType.EAGERis a property of the mapping, so it applies to every query that ever loads an order. The order list, the search and the dashboard now all load every line of every order, whether they use them or not.enable_lazy_load_no_transmakes Hibernate open a temporary session for each lazy read outside a transaction. Each read takes its own connection from the pool and runs its own query, so a loop over 500 orders sends 500 extra queries, one connection at a time.
Corrected implementation
@Componentclass OrderExportJob { private final OrderRepository orders; OrderExportJob(OrderRepository orders) { this.orders = orders; } @Scheduled(cron = "0 0 2 * * *") @Transactional(readOnly = true) public void export() { for (PurchaseOrder order : orders.findAllWithLines()) { // @EntityGraph(attributePaths = "lines") write(order.getId(), order.getLines()); } }}Why it is written this way
- The job states what it needs, the repository loads it in one query, and the mapping stays lazy for everyone else.
Trade-offs
- Each use case needs its own repository method or query. That is more code than one global switch, and it is the code that documents what each caller reads.
- Joining a large collection multiplies rows: an order with 200 lines comes back as 200 rows. For very large exports, read in batches by id.
Configuration
The settings that decide how long a session lives and how lazy reads behave.
spring.jpa.open-in-viewDefault true
- What it does
- Keeps a JPA session bound to the thread for the whole web request, so lazy loading works in controllers and during rendering.
- When to change it
- Set it explicitly, and to the same value in every environment. With false, lazy reads outside a transaction fail at once, in development too.
hibernate.enable_lazy_load_no_transDefault false
- What it does
- Lets Hibernate open a temporary session to load a lazy association outside any session.
- When to change it
- Leave it off. It turns one clear exception into many hidden queries and connections.
hibernate.default_batch_fetch_sizeDefault none
- What it does
- When one lazy collection is loaded, load up to this many others of the same kind in the same query.
- When to change it
- A value such as 50 softens the cost of lazy reads inside a transaction. It does not help once the session is closed.
Hands-on exercise
Make development fail the way production does
Reproduce both runs, then find out which statement each repair sends.
Steps · 0 of 4 done
What you should see
Part 1 returns 200 with the default and 500 with the property set to false, while part 2 fails in both runs. The join fetch and the entity graph each print one select with a join; the DTO method prints two selects. After the change the request returns 200 with open-in-view off.
What can go wrong
Returning entities from a REST controller
- Symptom
- The endpoint fails while writing JSON, or returns far more data than intended and runs dozens of queries.
- Cause
- The JSON serialiser walks every getter, so it touches every lazy association, after the transaction has ended.
- Fix
- Return DTOs from the service. The response shape then no longer depends on the entity mapping.
Passing an entity to another thread
- Symptom
- An
@Asyncmethod or a message handler fails on the first lazy read of an entity it was given. - Cause
- A session belongs to one thread. The entity is detached as far as the other thread is concerned.
- Fix
- Pass the id and load what is needed inside a transaction on the receiving thread.
Fixing the exception with a transaction around everything
- Symptom
@Transactionalis added to the controller or the job, the exception goes away, and response times grow.- Cause
- The lazy reads now succeed, one query each. The N+1 queries were hidden, not removed, and the connection is held for the whole method.
- Fix
- Keep the transaction small and fetch the association in the query that loads the parent.
How to troubleshoot
LazyInitializationException: could not initialize proxy - no Session
Check
The first frame of your own code in the stack trace, and which thread it ran on
- How to read it
- That frame is where the data was needed. The thread name tells you whether a web request, a scheduler or a pool thread ran it, and so whether open-in-view could have helped.
It fails in production and not locally
Check
The effective value of spring.jpa.open-in-view in both environments
- How to read it
- A difference here explains it completely. Set the same value everywhere, preferably false, so that the failure can be reproduced on a laptop.
No exception, but a page sends far more queries than expected
Check
spring.jpa.properties.hibernate.generate_statistics=true and the statement count per request
- How to read it
- A count that grows with the number of rows shown is lazy loading in a loop. Open-in-view lets it happen silently.
Key takeaways
- A lazy association loads only while the session that created it is open. After that the entity is detached and the read throws.
- Spring Boot keeps a session open for the whole web request by default, which hides the problem there and nowhere else.
- It fails in production because of a different setting, a different caller such as a job or listener, a cache, or tests that run inside a transaction.
- Load what the caller needs before the service returns: a join fetch, an entity graph or a DTO.
- Eager mappings and
enable_lazy_load_no_transremove the exception and add queries. Avoid both.
Practical check
Small scenarios, one decision each. Pick what you would do, then read why.
Scenario 1 of 2
GET /orders/{id} returns an order with its lines and has worked for a year. The team adds a Kafka listener that calls the same orderService.find(id) and then reads order.getLines(). The listener throws LazyInitializationException. spring.jpa.open-in-view is true.
Why does the listener fail when the endpoint does not?
Scenario 2 of 2
To stop a LazyInitializationException in an export job, a developer changes Customer.orders to FetchType.EAGER. The job works. The customer search page, which lists 200 customers and shows no orders, becomes several times slower.
What is the better repair for the job?
References
References: Spring Boot reference: SQL databases, Open EntityManager in View (enabled by default for web applications) ↗ · Hibernate ORM 6.6 User Guide: Fetching (lazy and eager, join fetch, entity graphs, batch fetching) ↗ · Spring Data JPA reference: JPA query methods (@Query, configuring fetch graphs with @EntityGraph) ↗ · Report a problem