Video in progress
What causes LazyInitializationException, and what is the right way to fix it?
It appears when you touch a lazy association after the session (transaction) has closed. The right fix is to load the data you need up front inside the transaction (fetch join, entity graph, DTO), not to stretch the session.
📖 Answer
@Transactional(readOnly = true)
public Order find(long id) { return repo.findById(id).orElseThrow(); }
// in the controller, outside the transaction:
order.getItems().size(); // LazyInitializationException: could not initialize proxy - no Session
items is a lazy collection: Hibernate put a placeholder there instead of a real list. Filling it needs a session, and the session was closed as soon as the service method returned.
The right ways:
- load what you need explicitly in the service and return a DTO:
@Query("select o from Order o join fetch o.items where o.id = :id") Optional<Order> findWithItems(long id); @EntityGraph(attributePaths = "items");- fetch only the columns you need with a projection.
Interviewees often slip here and offer these as the "solution":
FetchType.EAGER: the problem just moves elsewhere. Now it's always loaded even when you don't need it, and N+1 gets worse;hibernate.enable_lazy_load_no_trans=true: it opens a new session and connection for every lazy access, which is very expensive;- relying on Open Session in View: it works, but the queries quietly run in the view layer.
Sign up to mark studied questions and save your progress.