The order whose items cannot be read
A medium Java puzzle in the jpa and hibernate pitfalls family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.
Highlighted: line 13. Play this one as a puzzle without the answer.
What is wrong
service.find returns when its transaction ends, so the persistence context is closed. getItems is a lazy collection, and touching it outside the session throws LazyInitializationException. Open Session in View hides this in development but is often disabled in production.
The fix
How to avoid it next time
Load everything a use case needs in the service layer and return DTOs, not managed entities.
Want the background? Read Persistence context, flush and dirty checking in the Java concepts library.
About jpa and hibernate pitfalls
The persistence context, lazy loading and entity equality rules create bugs that look fine in a unit test and break once there is a real session, a real transaction or real data volume.
In code review: Ask where the session is open when a lazy field is read, how many queries a loop causes, and whether entity equals and hashCode depend on the generated id.
More puzzles in this family
Frequently asked questions
What is the bug in "The order whose items cannot be read"?
service.find returns when its transaction ends, so the persistence context is closed. getItems is a lazy collection, and touching it outside the session throws LazyInitializationException. Open Session in View hides this in development but is often disabled in production. The faulty line is line 13: return order.getItems().size();
How do I fix it?
Replace it with: Fetch what the controller needs inside the transaction: a service method returning a DTO, or a query with join fetch or an entity graph.. Load everything a use case needs in the service layer and return DTOs, not managed entities.
How do I catch jpa and hibernate pitfalls in code review?
Ask where the session is open when a lazy field is read, how many queries a loop causes, and whether entity equals and hashCode depend on the generated id.
Is there a new puzzle every day?
Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.