Skip to content

Path 5 · lesson 5 of 5

Intermediate18 minJava 21 (OpenJDK 21.0.13, HotSpot) · Spring Boot 3.5.16 · Hibernate ORM 6.6

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-view does 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=false in 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 @Async method has no web request and so no open session, whatever the setting.
  • Tests keep the session open. A test annotated with @Transactional runs 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 output
spring.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
Part 1: the HTTP request succeeds, because the request's session is still open when the controller reads the lines. Part 2: exactly the same read on a background thread fails with "could not initialize proxy - no Session", although open-in-view is on. Part 3: three repairs that work with no session open afterwards, with the number of SQL statements each one sent.

Program outputThe same, with --spring.jpa.open-in-view=false

Real JVM output
spring.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 Session
Now the HTTP request fails too: the controller's read throws, and the client receives a 500. Nothing in the code changed between the two runs, only one property. This is the difference between a development environment on the default and a production environment that switched it off.

Spring 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 output
2026-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
"spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering." Setting the property explicitly, to either value, removes the warning. It is asking you to make the choice on purpose.
RepairSQL statements in the labWhat it does
join fetch in the query1Loads the order and its lines in one statement with a join
@EntityGraph(attributePaths = "lines")1The same join, declared on the repository method instead of in the query text
Build a DTO inside the transaction2Reads 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"]
Where the session ends, and who touches the entity afterwards.
  • 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
The read happens after the only moment at which it could succeed.
  1. Only one query was sent, for the order. The lines were never asked for while it was possible.
  2. 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 cluster

Unplanned 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
Open the full animated lesson

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.

src/main/java/lab/OrderRepository.javaJava
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 findById stays available for callers that do not need the lines, so the join is only paid where it is used.

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

PurchaseOrder.java and application.properties (incorrect)Java
@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=true

Why it is written this way

  • Both changes are one line, and both make the exception disappear everywhere at once.

Why it fails

  • FetchType.EAGER is 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_trans makes 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

OrderExportJob.java (corrected)Java
@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 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 @Async method 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
@Transactional is 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_trans remove 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