Everything loads with everything
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 8. Play this one as a puzzle without the answer.
What is wrong
EAGER fetching loads the orders and tags whenever a customer is loaded, even by id for a simple name lookup, and each eager association can cascade into more queries or large joins. Two eager bags can also cause MultipleBagFetchException.
The fix
How to avoid it next time
Keep associations lazy and fetch exactly what a use case needs with a join fetch or entity graph.
Want the background? Read JPA relationships, cascade and orphan removal 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 "Everything loads with everything"?
EAGER fetching loads the orders and tags whenever a customer is loaded, even by id for a simple name lookup, and each eager association can cascade into more queries or large joins. Two eager bags can also cause MultipleBagFetchException. The faulty line is line 8: @OneToMany(mappedBy = "customer", fetch = FetchType.EAGER)
How do I fix it?
Replace it with: @OneToMany(mappedBy = "customer") List
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.