LazyInitializationException in JPA — Cause and Solutions
Fast recall
Quick revision
Core answer
Whether you understand the persistence-context lifecycle and can name the right fix versus the band-aid fixes
Enabling hibernate.enable_lazy_load_no_trans=true — a band-aid that hides bugs and causes silent N+1 plus connection-pool exhaustion
Distinguish the correct fix (keep the transaction open or use JOIN FETCH) from wrong fixes (Open Session In View, enable_lazy_load_no_trans)
Interview-ready guide
Interview answer
A controller receives a detached Order and Jackson calls order.getItems(); Hibernate then cannot initialize the collection. A service method can load an OrderDetail DTO with the required items while its transaction/persistence context is active and return that DTO. If business code truly performs several lazy operations as one unit, an appropriate @Transactional service boundary can be correct—but it should match the use case rather than blanket the controller.
For example, returning an Order entity and accessing its lazy items after the service transaction ends can fail. I load the endpoint's required data inside the transaction, usually into a DTO, instead of relying on a session in the web layer.
LazyInitializationException in JPA — Cause and Solutions
Direct Answer
Hibernate throws LazyInitializationException when code tries to initialize unfetched lazy state without an open Session that can load it. The transaction may have ended, the entity may be detached, or the Session may be closed. Fix the use case by fetching the required data inside a clear boundary or projecting a DTO. Simply widening every transaction can hide over-fetching and long-transaction problems.
Common Mistakes & Pitfalls
- Enabling enable_lazy_load_no_trans — it stops the exception by opening a new session on each lazy access, trading one bug for severe N+1 and pool exhaustion.
- Relying on Open Session In View —
spring.jpa.open-in-view=true(Spring Boot's default) keeps the session open for the whole request, hiding the exception but encouraging data access in controllers and N+1 in views. Disable it in production. - Switching everything to EAGER — avoids the exception but loads unneeded data on other queries; keep lazy and fix the transaction boundary instead.
Check your understanding
Answer these without looking back at the article.
- What is Open Session In View and why is it considered an anti-pattern?
- How does @Transactional keep the JPA session open?
- What is the best practice for avoiding LazyInitializationException in REST APIs?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.