Video in progress

Why does LazyInitializationException get thrown?

It is thrown when you access a lazy proxy or collection after the persistence context (session) has been closed. Hibernate needs to read the data, but there is no open session anymore.

📖 Answer

A typical case:

@Transactional
public Order getOrder(Long id) {
    return orderRepo.findById(id).orElseThrow();
}

// in the controller, the transaction has already ended:
order.getItems().size(); // LazyInitializationException: could not initialize proxy - no Session

The right fixes:

  • load the data you need inside the transaction: JOIN FETCH or @EntityGraph;
  • return a DTO from the service instead of an entity, and build the DTO inside the transaction;
  • use a dedicated query that fetches only the columns you need (a projection).

Bad "fixes" that you see often:

  • switching to FetchType.EAGER: the error goes away, but now you over-fetch everywhere;
  • hibernate.enable_lazy_load_no_trans=true: it opens a separate session for every lazy access, which is the worst form of N+1;
  • relying on open-in-view.

If you answer "I'll make it EAGER" in an interview, the next question is usually about the cost of that choice.