Two new entities that are equal
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 12. Play this one as a puzzle without the answer.
What is wrong
New entities have a null id until they are persisted, so any two unsaved products compare equal, and putting both in a HashSet keeps one. Worse, hashCode changes when the id is assigned, which breaks the entity inside hash collections.
The fix
How to avoid it next time
Do not base equals and hashCode on a generated id. Use a natural key or follow the documented Hibernate pattern.
Want the background? Read equals() and hashCode() 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 "Two new entities that are equal"?
New entities have a null id until they are persisted, so any two unsaved products compare equal, and putting both in a HashSet keeps one. Worse, hashCode changes when the id is assigned, which breaks the entity inside hash collections. The faulty line is line 12: return o instanceof Product p && Objects.equals(id, p.id);
How do I fix it?
Replace it with: Use a stable business key (such as sku) in equals/hashCode, or a constant hashCode with id-based equals only when id != null.. Do not base equals and hashCode on a generated id. Use a natural key or follow the documented Hibernate pattern.
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.