Quick revision
The short answer
equals returns true for the same reference, then checks that the other object is the same kind of entity in a proxy-safe way, and finally returns id != null && id.equals(other.getId()), reading the other id through its getter. hashCode returns a constant for the class, so it stays the same when the database assigns the id. A constant hash is fine because entity sets are small; the alternative is an immutable business key or a UUID assigned at construction.
What to remember
In this answer, we saw that a database-generated id is null until persist, so an id-based hashCode moves the entity to another bucket and HashSet loses it. The working version checks the same reference, accepts proxies with instanceof, compares ids through the getter only when the id is not null, and returns a constant hash per class. An immutable business key or a UUID assigned at construction is the alternative when we want a distributed hash.
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.
equals returns true for the same reference, then checks that the other object is the same kind of entity in a proxy-safe way, and finally returns id != null && id.equals(other.getId()), reading the other id through its getter. hashCode returns a constant for the class, so it stays the same when the database assigns the id. A constant hash is fine because entity sets are small; the alternative is an immutable business key or a UUID assigned at construction.
Why this question is asked
Entities live in HashSets more often than we think: a @OneToMany mapped as a Set, a set of selected items in a service, a cache keyed by entity. If equals and hashCode are wrong, items vanish from sets after a save, duplicates appear, or comparisons fail only when Hibernate hands us a proxy. Interviewers ask for this code because getting it right needs an understanding of three things at once: the hashCode contract, the moment the id appears, and how proxies work. In this answer, we will recap those three, write a broken version, see exactly how it fails, and then write the version that works.
1A Quick Recap of the Three Constraints
The hashCode contract says that if two objects are equal, they must have the same hash, and that the hash of an object must not change while it sits in a hash-based collection. A HashSet uses the hash to choose a bucket, so if the hash changes later, the set looks in the wrong bucket and cannot find the object.
With a database-generated id, for example an identity column or a sequence, the id is null when we create the entity with new and gets its value only when we call persist or save. So the id is not stable across the life of the object: it goes from null to a number.
A Hibernate proxy is a subclass that Hibernate generates at runtime to stand in for an entity that has not been loaded yet. Its class is something like Book$HibernateProxy$x7Lq2, and until it is initialized, its own fields are empty; it only knows its id. Any equals that compares getClass() or reads fields directly from the other object will treat a proxy as different from the real entity.
2The Version That Looks Right but Breaks
A first attempt uses the id in both methods, which is what IDE generators produce.
Two bugs show up. contains returns false for an object that is in the set, and two different new books are equal because null equals null. And there is a third, hidden one: getClass() != o.getClass() returns true when o is a proxy of the same book, and reading ((Book) o).id directly from an uninitialized proxy gives null even if the book has id 1.
3Why the id-Based hashCode Breaks the HashSet
When we added the book, the set called hashCode, got the hash of null, and placed the book in the bucket for that hash. After persist, the id is 1, so hashCode returns a different number. contains computes the new hash, looks in a different bucket, finds nothing there and returns false. The book is still in the set, in its old bucket, but now we can neither find it nor remove it.
- add(book)
hashCode()with id null picks bucket 0 - persist(book)database assigns id 1
- contains(book)
hashCode()with id 1 picks bucket 5 - Bucket 5 is emptycontains returns false, remove does nothing
4 steps in order. Play them, or step through them one at a time.
The object never moved; its hash did.
4Writing equals and hashCode That Work
The fix keeps the id for equality but takes it out of the hash, handles proxies, and treats a missing id as unknown rather than equal.
Notice each decision. The same-reference check makes a new entity equal to itself before it has an id. instanceof accepts the proxy, because the proxy class extends Book. Calling other.getId() instead of reading other.id matters because the proxy's own id field is empty, while its getter is intercepted and returns the identifier without a database query. The id != null check means two unsaved books are never equal, which is correct because we do not know yet whether they are the same row.
We use the class literal Book.class rather than getClass() in hashCode, because getClass() on a proxy returns the proxy class and would give a proxy a different hash from the real object that it equals. If Book is part of an entity hierarchy where subclasses must not equal each other, replace instanceof with a comparison of effective classes, using Hibernate.getClass or the proxy's persistent class; check your version for which one avoids initializing the proxy.
5Is a Constant hashCode a Performance Problem?
With a constant hash, every Book goes into the same bucket, so a set of books behaves like a list and lookups compare against each element. But entity collections we keep in memory hold tens or hundreds of items, not millions, so the trade is a small cost in an uncommon situation for correctness everywhere.
If we want a well-distributed hash, we need a value that exists from construction and never changes. A natural business key such as an ISBN works, as long as it is truly immutable. An application-assigned UUID, set in the field initializer, also works, and then both equals and hashCode can simply use it, because it is there before persist and never changes.
6Follow-up questions
Why does using the id directly in hashCode break a HashSet after persist?
Because the HashSet stored the entity in a bucket chosen from the hash at the time of add, when the id was null. Persist gives the entity an id, so hashCode returns a different number afterwards. contains and remove compute the new hash, look in another bucket and do not find the entity, even though it is still in the set in its old bucket.
Why not compare all fields, like a value object?
Because entities are identified by identity, not by their current values. A book whose title we correct is still the same book, and mutable fields in the hash give the same lost-in-the-set effect.
Should equals and hashCode be final?
Some templates make them final, and then the proxy cannot override them, so the method runs on the proxy object itself with empty fields. That works only if every field access goes through getters, as in our equals. Leaving them non-final is simpler: the proxy delegates the call to the loaded entity, at the cost of possibly initializing it.
7Conclusion
In this answer, we saw that a database-generated id is null until persist, so an id-based hashCode moves the entity to another bucket and HashSet loses it. The working version checks the same reference, accepts proxies with instanceof, compares ids through the getter only when the id is not null, and returns a constant hash per class. An immutable business key or a UUID assigned at construction is the alternative when we want a distributed hash.
Open with
The difficulty is that a generated id is null until persist, and Hibernate may give me a proxy subclass instead of the real entity. So in equals I first return true for the same reference, which makes a new entity equal to itself.
Then, if they want more
Then I check o instanceof Book, which a Hibernate proxy passes because it extends Book. Then I return id != null && id.equals(other.getId()). I read the other id through the getter because a proxy's own fields are empty, but its getId is intercepted and answers without a query. And the null check means two unsaved books are never equal.
For hashCode I return a constant, Book.class.hashCode(). If I used the id, a book added to a HashSet before persist would be hashed with null, and after persist its hash would change, so contains and remove would look in the wrong bucket and fail. I use the class literal rather than getClass because a proxy's getClass is the proxy class.
The constant hash makes a set behave like a list, but entity sets are small, so that is acceptable. If I want a real hash, I use an immutable business key, or assign a UUID at construction and base both methods on it.
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
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
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 "Write equals and hashCode for an entity with a database-generated Long id so that it...": https://scrivio-interview-library.netlify.app/databases/jpa-relationships/a8a8cd2579/