Quick revision
The short answer
Before persist the id is null, so hashCode() returns one value and the HashSet stores the entity in the bucket for that hash. After persist and flush the database-generated id is filled in, hashCode() returns a different value, and contains() looks in the bucket for the new hash, where the entity is not. The fixes are to base equality on a natural business key set at creation, to use the id in equals but return a constant hashCode for the class, or to assign ids in the application, such as a UUID generated in the constructor.
What to remember
In this answer, we saw that an entity whose equals and hashCode use a database-generated id changes its hash code when persist and flush fill in the id. HashSet stored it in the bucket for the old hash and now looks in the bucket for the new one, so contains() returns false while the element is still inside. We fixed it with a natural business key set at creation, with id-based equals plus a constant hashCode for the class, or with ids assigned in the application such as UUIDs generated at construction.
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 persist the id is null, so hashCode() returns one value and the HashSet stores the entity in the bucket for that hash. After persist and flush the database-generated id is filled in, hashCode() returns a different value, and contains() looks in the bucket for the new hash, where the entity is not. The fixes are to base equality on a natural business key set at creation, to use the id in equals but return a constant hashCode for the class, or to assign ids in the application, such as a UUID generated in the constructor.
Why this question is asked
This bug is a favourite in interviews because it combines two topics people often learn separately: how HashSet finds elements and how JPA assigns identifiers. In production it shows up as duplicate rows, child entities that cannot be removed from a collection, or caches that never hit. In this answer, we will recap how HashSet uses hashCode, reproduce the problem, trace exactly why contains() returns false, and then compare three fixes and when each one fits.
1A Quick Recap of How HashSet Finds an Element
A HashSet is a HashMap underneath. When we add an object, the set calls its hashCode(), uses that number to choose a bucket in an internal array, and stores the object there. When we later call contains(), the set calls hashCode() again, goes to the bucket for that value, and only then calls equals() on the objects in that bucket.
So the set relies on one quiet promise: an object's hash code must not change while the object is inside the set. If it changes, the set will look in the wrong bucket and never even call equals() on the stored object.
2Reproducing the Problem
Here is an entity whose equals and hashCode use the generated id, which is a common pattern copied from tutorials.
Notice that the very same object, the one in the set, is no longer found. The set still holds it, iterating over the set still returns it, and size() is still 1. Only hash-based lookups, contains() and remove(), are broken.
3Why the Lookup Misses
When we added the tag, its id was null, and Objects.hashCode(null) is 0, so the set placed it in the bucket for 0. Persisting and flushing ran the INSERT, the database generated 42, and Hibernate wrote 42 into the id field of our object.
Now contains(tag) calls hashCode() again and gets 42. It goes to the bucket for 42, finds nothing there, and returns false. It never looks in bucket 0, where the object actually sits. The equals() method would have said true, but it never gets called. So the root cause is that the hash code depends on a field that changes during the object's life.
| Moment | tag.id | hashCode() | Bucket used by contains() |
|---|---|---|---|
After tags.add(tag) | null | 0 | 0, where the tag is stored |
| After persist and flush | 42 | 42 | 42, which is empty |
4Fix 1: Use a Natural Business Key
If the entity has a business key that is set when the object is created and never changes, such as an ISBN for a book, an order number or a tag's unique name, we can use it for equality. It is available before and after persisting, so the hash code never changes.
This is the cleanest fix when such a key truly exists. The catch is that many entities have no immutable business key, and inventing one, or using a field that users can edit, brings the same problem back.
5Fix 2: Id-Based equals With a Constant hashCode
When there is no natural key, a widely used pattern compares ids only when the id is not null and returns the same hash code for every instance of the class.
Because the hash code is the same before and after persisting, the set always looks in the right bucket, and equals() then decides. Two new, unsaved tags are not equal to each other, which is correct, because they will become two different rows. The cost is performance: all tags in a hash set share one bucket, so lookups become linear in a large set. For the typical case, a collection of a few dozen children on an aggregate, that cost is negligible, which is why this pattern is popular. With Hibernate proxies, compare using instanceof rather than getClass(), since a proxy is a subclass.
6Fix 3: Assign the Id in the Application
The third option removes the cause entirely: give the entity its identity when it is constructed, so the id is never null. A UUID generated in the constructor or field initialiser works well, and UUID version 7 values are time-ordered, which is kinder to database indexes than random version 4 values.
| Fix | Works when | Cost |
|---|---|---|
| Natural business key | An immutable key exists at creation | None, if the key truly never changes |
Id equals, constant hashCode | No natural key; small collections | Linear lookups in large hash sets |
| Application-assigned UUID | We control id creation | Larger keys; save() needs isNew handling |
Now equality is stable from the first moment and fits DDD well, since an entity's identity exists before persistence. Notice that we do not use @GeneratedValue here. With an assigned id, Spring Data's save() cannot use a null id to tell a new entity from an existing one, so it calls merge(), which may first run a SELECT; adding a @Version field or implementing Persistable fixes that. Check your Spring Data version for the details of isNew().
7Follow-up questions
Why not just add the entity to the set after persisting?
That works for that one code path, but it relies on every developer remembering the rule forever. Entities are added to collections in many places, often before the cascade persist that saves them, so a design where equality is always stable is far safer than a convention.
Does the same problem affect HashMap keys and Hibernate's own collections?
Yes. Any hash-based structure that holds the entity is affected, including a HashMap used as a cache and a Set mapped as a @OneToMany. A common symptom is that orphanRemoval fails to delete a child because remove() cannot find it in the set.
Is it fine to use all fields in equals, as Lombok's @Data does?
No. Any mutable field then changes the hash code, which causes the same bug on every update, and it can trigger lazy loading of associations inside equals or hashCode. Entities need identity-based equality.
8Conclusion
In this answer, we saw that an entity whose equals and hashCode use a database-generated id changes its hash code when persist and flush fill in the id. HashSet stored it in the bucket for the old hash and now looks in the bucket for the new one, so contains() returns false while the element is still inside. We fixed it with a natural business key set at creation, with id-based equals plus a constant hashCode for the class, or with ids assigned in the application such as UUIDs generated at construction.
Open with
The problem is that the hash code changes while the object is inside the set. Before persist, the generated id is null, so hashCode returns, say, zero, and the HashSet puts the entity in the bucket for zero.
Then, if they want more
Persist and flush run the insert and Hibernate writes the generated id, say 42, into the object. Now contains calls hashCode again, gets 42, goes to that bucket, finds nothing and returns false. It never calls equals on the object, which is still sitting in bucket zero; size still says one, and iteration still finds it.
Remove and orphan removal break the same way. I know three fixes. If the entity has a natural business key that is set at creation and never changes, like an ISBN or a unique tag name, I base equals and hashCode on that.
If there is no such key, I use the id in equals only when it is non-null, so two unsaved entities are equal only if they are the same object, and return a constant hashCode for the class, so the hash never changes; that makes big hash sets slower, but collections of children are usually small.
Or I assign the id in the application, a UUID generated when the object is constructed, ideally time-ordered like version 7, so the id is never null; then I make sure Spring Data still knows the entity is new, for example with a version field.
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 official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
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 "A JPA entity implements equals and hashCode using its database-generated id. A new...": https://scrivio-interview-library.netlify.app/java/domain-driven-design/92acf72a67/