Video in progress
How do you fix `LazyInitializationException` the right way, and why is `enable_lazy_load_no_trans` a bad solution?
The right way is to load the data you need explicitly inside the transaction: fetch join, entity graph, DTO projection. hibernate.enable_lazy_load_no_trans=true opens a new temporary session and connection for every lazy access, which hides N+1 and breaks isolation.
📖 Answer
The error is actually a useful signal: "you didn't plan to load this data". You shouldn't silence it, you should fix the plan.
What happens with enable_lazy_load_no_trans on: the transaction has ended, but order.getItems() is called. Hibernate opens a new session, takes a connection from the pool, runs a SELECT, and closes it. For a list of 200 orders that's 200 separate connections and queries, each in its own "transaction", so the data isn't consistent across them. The Hibernate documentation also calls this an anti-pattern.
Calling Hibernate.initialize(order.getItems()) inside the service works, but that's also a separate query for each one.
The right fixes, depending on the case:
// 1. an explicit query
@Query("select o from Order o join fetch o.items where o.id = :id")
Optional<Order> findWithItems(Long id);
// 2. an entity graph
@EntityGraph(attributePaths = "items")
Optional<Order> findById(Long id);
// 3. only the data you need
record OrderSummary(Long id, int itemCount) {}
In async code this error shows up especially often: people pass an entity to an @Async method or a CompletableFuture, which runs on another thread, without a transaction. Pass an id or a ready DTO there instead of the entity, and let the new thread load what it needs in its own transaction.
The same goes for event listeners: inside @TransactionalEventListener(phase = AFTER_COMMIT) there's no transaction, so don't touch lazy fields.
Sign up to mark studied questions and save your progress.