Sobes.tech
Senior

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.LAZY are 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:

  1. Open a session during access to lazy data (Open Session In View) — suitable for web applications, but may lead to undesirably long sessions.

  2. Initialize lazy collections or objects in advance within an active session, for example, using Hibernate.initialize() or calling getters.

  3. Use fetch = FetchType.EAGER for necessary associations if lazy loading is not needed (but this can lead to excessive queries).

  4. 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();
  1. DTO projections — load only necessary data into separate objects.

The choice of approach depends on the application's architecture and performance requirements.