What is LazyInitializationException in Hibernate and how to work with it?
sobes.tech AI
Answer from AI
LazyInitializationException in Hibernate occurs when there is an attempt to access a lazily loaded (lazy) associated object outside of a Hibernate session.
Reason:
- Associated entities marked as
FetchType.LAZYare not loaded immediately, but only upon first access. - If the Hibernate session is already closed (for example, after exiting a transaction), attempting to access such data causes an exception.
How to handle this problem:
-
Open a session during access to lazy data (Open Session In View) — suitable for web applications, but may lead to undesirably long sessions.
-
Initialize lazy collections or objects in advance within an active session, for example, using
Hibernate.initialize()or calling getters. -
Use
fetch = FetchType.EAGERfor necessary associations if lazy loading is not needed (but this can lead to excessive queries). -
Use join fetch queries to load associated entities immediately:
String hql = "from Order o join fetch o.items where o.id = :id";
Order order = session.createQuery(hql, Order.class)
.setParameter("id", orderId)
.uniqueResult();
- DTO projections — load only necessary data into separate objects.
The choice of approach depends on the application's architecture and performance requirements.