Persistence contextmedium3-5 years

A service returns an `Order`, and the controller calls `order.getLines()` and gets `LazyInitializationException: could not initialize proxy - no Session`. One teammate suggests making `lines` EAGER; another says just keep `spring.jpa.open-in-view=true`. What is the exception actually telling you, and what is the right fix?

A lazy relationship is a proxy that holds a reference to the session it was created in and runs its SELECT the first time something calls it. The service's transaction ended when the method returned, so the session closed and the Order became detached; when the controller finally touched lines, the proxy tried to fetch through a closed session and failed. The exception is telling you something true: this code is reading data the transaction never decided to load. Making the relationship EAGER or keeping open-in-view both make the symptom stop and both are the wrong move. The fix is to decide inside the transaction: fetch what the caller needs in the query (a fetch join or an entity graph), or map to a DTO inside the transaction so what leaves the service is a value, not a live handle.

The lesson behind it →
More on Persistence context