Deleting an order deletes the customer
A hard 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 7. Play this one as a puzzle without the answer.
What is wrong
CascadeType.ALL includes REMOVE, so removing an order also removes its customer, which fails on a foreign key violation or silently deletes the customer's other data. Cascades suit parent-owned children, not shared references.
The fix
How to avoid it next time
Cascade only from an owner to the objects it exclusively owns, usually on @OneToMany. Never cascade REMOVE on @ManyToOne.
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 "Deleting an order deletes the customer"?
CascadeType.ALL includes REMOVE, so removing an order also removes its customer, which fails on a foreign key violation or silently deletes the customer's other data. Cascades suit parent-owned children, not shared references. The faulty line is line 7: @ManyToOne(cascade = CascadeType.ALL)
How do I fix it?
Replace it with: @ManyToOne(fetch = FetchType.LAZY) Customer customer; // no cascade. Cascade only from an owner to the objects it exclusively owns, usually on @OneToMany. Never cascade REMOVE on @ManyToOne.
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.