Quick revision
The short answer
Before the parent is saved, every new Order has a null id, so the orders hash alike and, depending on how equals() treats null, may even count as equal, so the HashSet can keep only one of them. When Hibernate persists them, each id is set, the hash changes, and the orders now sit in buckets that no longer match their hash, so contains() and remove() fail and duplicates can appear. The accepted options are a stable, immutable business key, id-based equals() with a constant hashCode() for the entity class, or a UUID assigned when the object is constructed; whichever we choose, entities should not be used as keys in hash-based collections outside one persistence context, and the team should document its convention.
What to remember
In this answer, we saw that id-based equals() and hashCode() break for new entities: before persist the id is null, so new orders hash alike and may even be merged into one, and after persist the id and hash change, so the set cannot find them and duplicates appear. The options are a stable business key, id-based equals() with a constant hashCode(), or a UUID assigned at construction, each with its own cost. Entities should not be used as keys in hash-based collections beyond one persistence context, and the team should document its chosen convention.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Before the parent is saved, every new Order has a null id, so the orders hash alike and, depending on how equals() treats null, may even count as equal, so the HashSet can keep only one of them. When Hibernate persists them, each id is set, the hash changes, and the orders now sit in buckets that no longer match their hash, so contains() and remove() fail and duplicates can appear. The accepted options are a stable, immutable business key, id-based equals() with a constant hashCode() for the entity class, or a UUID assigned when the object is constructed; whichever we choose, entities should not be used as keys in hash-based collections outside one persistence context, and the team should document its convention.
Why this question is asked
Entity equality is one of the oldest debates in JPA, and it matters because Hibernate puts entities into Sets all the time: one-to-many collections, the persistence context and our own code. The bug in this review is easy to miss, because everything works for entities loaded from the database, where the id is already set, and only fails for new ones. Interviewers ask it to see whether we can connect HashSet internals with the entity life cycle and choose a pattern deliberately. In this answer, we will recap when JPA assigns a generated id, reproduce what goes wrong in the set, look at the three accepted patterns and their trade-offs, and finish with the team convention.
1A Quick Recap: When a Generated id Appears
With @GeneratedValue, the database or Hibernate chooses the primary key, so a new Order created with new Order() has id == null. The id is assigned when the entity becomes persistent: for IDENTITY columns Hibernate inserts the row immediately on persist, and for SEQUENCE it fetches the next value at persist time. For children saved through cascade from a parent, that happens when the parent is saved or flushed. So the id of each order changes from null to a number at a moment the code adding orders to the set does not see.
A HashSet stores each element in the bucket chosen by the element's hashCode() at the moment it was added and remembers that hash in the node. If the hash changes later, the set can no longer find the element.
2Reproducing What Goes Wrong
Here is the entity from the review and the code that adds orders before saving the customer.
| Moment | id | hashCode() | Set can find it? |
|---|---|---|---|
new Order(), added to set | null | 0 | yes, stored under hash 0 |
second new Order() added | null | 0 | treated as equal: not added |
| after save or flush | 101 | 101 | no: node still holds hash 0 |
| loaded later in a new session | 101 | 101 | yes, stored under 101 |
Notice the two separate failures. Before saving, Objects.equals(null, null) is true, so all new orders are equal and the set deduplicates real, different orders into one. After saving, the surviving order has a new hash, so the set cannot find it: contains() and remove() return false, and adding it again creates a duplicate. If equals() instead treats null ids as unequal, the first problem goes away, but every new order still hashes to 0 and every one moves bucket after the save.
3Option 1: A Stable Business Key
If the entity has a natural identity that exists from construction and never changes, such as an order number issued by the business, equality can use it. Hibernate's @NaturalId marks such a field and also allows lookups by it.
This is the cleanest option when such a key really exists and is truly immutable. Many entities do not have one; an email address or a name looks stable until the day it changes.
4Option 2: id-Based equals() With a Constant hashCode()
When there is no business key, a widely used pattern keeps id-based equality but makes hashCode() the same for every instance of the class, so it can never change.
Notice the two changes. A null id means not equal to anything but itself, so new orders are not merged. And because the hash is constant, saving the entity does not move it. The cost is that every Order in one HashSet lands in the same bucket, so lookups in that set are slow for very large sets. Entity collections are usually small, tens or hundreds of elements, so this is an accepted trade-off. We use other.getId() rather than the field, because the other object may be a lazy proxy whose fields are not initialised.
5Option 3: Assign a UUID at Construction
A third option is to give each entity its identity in Java, before it ever reaches the database. Either the primary key itself is a UUID set in the field initialiser, or the entity has a separate immutable uuid column used only for equality.
| Pattern | Stable across save? | Main cost |
|---|---|---|
equals/hashCode on generated id | no | the bug in this review |
Business key (@NaturalId) | yes, if the key never changes | needs a truly immutable key |
id equals + constant hashCode | yes | one bucket per set: slow for huge sets |
| UUID assigned at construction | yes | bigger, less index-friendly keys |
| No override (identity) | yes, within one session | different sessions give unequal copies |
Equality and hashing are now stable across the whole life cycle. The costs are a larger key, 16 bytes instead of 8, random values that index less efficiently in B-trees than sequential ones (time-ordered UUIDs such as version 7, generated by a library, reduce this), and the need for a @Version field or isNew() so Spring Data's save() does not assume the entity already exists.
6Keep Entities Out of Long-Lived Hash Keys
Whatever pattern we choose, entities are mutable, tied to a session and may be proxies, so they make poor keys for maps and sets that outlive one persistence context. A cache keyed by Order, or a set of Customer objects kept across requests, invites exactly this class of bug. In those places we key by the id value, a Long or UUID, or by a small immutable record built from the business key.
Finally, because Hibernate's own guidance accepts several patterns, the team should pick one per kind of entity and write it down in the coding conventions, with a test, so each new entity does not restart the debate.
7Follow-up questions
Does leaving equals() and hashCode() as Object's defaults avoid the problem?
Partly. Identity-based equality never changes, so sets behave within one session, and Hibernate guarantees one instance per row inside a persistence context. But an entity loaded in two sessions gives two unequal objects, so merging detached entities into sets can produce duplicates. It is acceptable for simple applications and is the default many teams start with.
Why use instanceof instead of getClass() in entity equals()?
Because Hibernate may hand us a proxy, a generated subclass of Order, for a lazy association. getClass() would then differ from Order.class and equals() would return false for the same row. instanceof accepts the subclass. Hibernate also offers Hibernate.getClass(o) to unwrap a proxy when an exact class check is needed.
Is this only a Hibernate problem?
No. Any object whose identity is assigned after it is added to a hash-based collection has the same problem. JPA just makes it common, because generated ids are the default.
8Conclusion
In this answer, we saw that id-based equals() and hashCode() break for new entities: before persist the id is null, so new orders hash alike and may even be merged into one, and after persist the id and hash change, so the set cannot find them and duplicates appear. The options are a stable business key, id-based equals() with a constant hashCode(), or a UUID assigned at construction, each with its own cost. Entities should not be used as keys in hash-based collections beyond one persistence context, and the team should document its chosen convention.
Open with
The problem is that the id is generated, so it is null until Hibernate persists the order, which for cascaded children happens when the parent is saved or flushed.
Then, if they want more
While it is null, every new order has the same hash, and with Objects.equals on the id, two new orders are even equal, so the HashSet silently keeps only one of them.
Once the save assigns an id, the hash changes, but the set stored the node under the old hash, so contains and remove fail and adding the order again creates a duplicate. I would recommend one of three accepted patterns.
If there is a real, immutable business key, like an order number set in the constructor, I base equals and hashCode on it, possibly marked with @NaturalId.
If there is not, I keep id-based equals but treat a null id as equal only to itself, and return a constant hashCode for the class, so the hash never changes; the cost is that all orders in a set share a bucket, which is fine for typical collection sizes.
The third option is assigning a UUID when the object is constructed, which is stable from the start but makes keys larger and needs a version field for Spring Data. I would use instanceof and getters in equals because of Hibernate proxies.
Beyond that, I would avoid entities as keys in maps or sets that outlive a persistence context, keying by id or a small record instead, and I would write the chosen convention down for the team.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.HashMap, API documentation, The Collections Framework, overview
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "In a code review you see a JPA entity Order whose equals and hashCode use the generated...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/4311f414ee/