Sobes.tech
Middle

In what cases does LazyInitializationException occur in Hibernate?

sobes.tech AI

Answer from AI

A LazyInitializationException in Hibernate occurs when attempting to access a lazily loaded associated object outside the context of an active Hibernate session. This typically happens if the session has already been closed, and you try to initialize an object that was loaded with lazy loading.

For example, if you have an entity with a lazy association:

@Entity
class User {
    @OneToMany(fetch = FetchType.LAZY)
    private Set<Order> orders;
}

And you load the user in one session, then try to access user.getOrders() after the session has been closed, you'll get a LazyInitializationException.

To avoid this, you can:

  • Use fetch = FetchType.EAGER (but this can lead to excessive data loading).
  • Open a session during the time you access lazy collections (Open Session in View).
  • Explicitly initialize collections within the session using Hibernate.initialize() or join fetch queries.

Example of initialization within a session:

Session session = sessionFactory.openSession();
User user = session.get(User.class, userId);
Hibernate.initialize(user.getOrders()); // initialize lazy collection
session.close();
// now it's safe to access user.getOrders()
In what cases does LazyInitializationException occur… - sobes.tech