Middle — Middle+
What are the ways to prevent LazyInitializationException in Hibernate?
sobes.tech AI
Answer from AI
LazyInitializationException occurs when attempting to access a lazily loaded (lazy) associated object outside of a Hibernate session.
Ways to prevent this error:
-
Initialize data within the session:
- Use
Hibernate.initialize()or call getters to load lazy collections/objects before closing the session.
- Use
-
Use FetchType.EAGER:
- Replace lazy loading with eager loading so related data is loaded immediately.
- Minus — it can lead to over-fetching of data.
-
Use JOIN FETCH in JPQL/HQL:
- Explicitly specify loading of related entities during selection.
-
Open Session in View (OSIV):
- Keep the Hibernate session open during request processing (e.g., in web applications).
- Allows lazy loading in presentation layers.
-
DTOs and projections:
- Load necessary data into DTO objects via queries to avoid accessing lazy collections after the session is closed.
Example of using JOIN FETCH:
String hql = "FROM Order o JOIN FETCH o.items WHERE o.id = :id";
Order order = session.createQuery(hql, Order.class)
.setParameter("id", orderId)
.uniqueResult();
// items are loaded together with the order
The choice of method depends on the application's architecture and performance requirements.