Quick revision
The short answer
A generated id is null until the entity is persisted, so an equals and hashCode based on it change their result after save, and a Book already in a HashSet can no longer be found. The best basis is a natural id that is assigned when the object is created and never changes, because it gives stable equality before and after persist. Without one, we use the id in equals, treating null ids as different, with a constant hashCode, and in every case we compare types with instanceof rather than getClass() because of Hibernate proxies; records cannot be entities, and Lombok's @Data equality over all fields is wrong for them.
What to remember
In this answer, we saw that equality based on a generated id breaks a HashSet twice: all new entities are equal while their ids are null, and the hash code changes after persist. An immutable natural id assigned at creation gives stable equals and hashCode; without one, we use the id with null treated as unequal and a constant hashCode. We compare with instanceof and getters because of proxies, and we keep records and Lombok's @Data equality away from entities.
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.
A generated id is null until the entity is persisted, so an equals and hashCode based on it change their result after save, and a Book already in a HashSet can no longer be found. The best basis is a natural id that is assigned when the object is created and never changes, because it gives stable equality before and after persist. Without one, we use the id in equals, treating null ids as different, with a constant hashCode, and in every case we compare types with instanceof rather than getClass() because of Hibernate proxies; records cannot be entities, and Lombok's @Data equality over all fields is wrong for them.
Why this question is asked
Equality of entities sounds like a style question until a Set<Book> in a mapped collection loses elements, or Hibernate deletes and reinserts a whole collection, or two different new books count as one. Entities are unusual objects: their identity comes from a database row, the id may not exist yet, and Hibernate may hand us a proxy instead of the real class. Interviewers ask this to see whether we can reason about all of that at once. In this answer, we will recap the HashSet contract, reproduce the broken id-based version, then look at the natural id solution, the constant hashCode solution, proxies, and why records and Lombok @Data do not fit.
1A Quick Recap of What a HashSet Needs
A HashSet stores each element in a bucket chosen from its hashCode() at the moment the element is added, and it finds elements again by computing the hashCode() and checking equals() inside that bucket. So the contract has two parts that matter here: equal objects must have equal hash codes, and the hash code of an object must not change while it is in the set. If it changes, the set looks in the wrong bucket and reports that the element is missing, even though it is still stored inside.
A Set<Book> mapped as a one-to-many or many-to-many collection is exactly such a set, and Hibernate also compares elements when it decides what to insert or delete in the collection table.
2Reproducing the Problem With a Generated Id
Here is the natural first attempt: equality based on the generated id.
| Moment | a.id | a.hashCode() | books.contains(a) |
|---|---|---|---|
new Book(), added to set | null | 0 | true |
| after persist and flush | 1 | 1 | false |
| second new Book added | null | 0 | add returns false |
Notice the two separate failures. Before persist, all new books are equal to each other because null equals null, so the set refuses the second book. After persist, the hash code changes from 0 to 1, so the set can no longer find the first book. In a mapped collection this shows up as elements that cannot be removed, or as duplicates after a merge.
3Solution 1: Use an Immutable Natural Id
If the entity has a business key that is set in the constructor and never changes, such as the ISBN, equality based on it is stable from the moment the object exists. It is the same before and after persist, in every session, and for detached copies.
This is the preferred solution whenever such a key exists, and it is one of the strongest reasons to map a @NaturalId at all.
4Solution 2: Id-Based Equals With a Constant hashCode
Many entities have no natural key. Then we keep the id as the identity but fix both failures: equals treats a null id as never equal to anything except the same object, and hashCode returns a constant for the class, so it cannot change when the id is assigned.
The cost is that all books share one bucket, so a HashSet of books degrades to a list scan. For entity collections of tens or hundreds of elements that does not matter; for huge in-memory sets it would, but entity collections should not be huge anyway. A common variant writes getClass().hashCode(), but Book.class.hashCode() is safer, because for a proxy getClass() returns the generated subclass and would give a different value from the real Book.
5Watch Out for Hibernate Proxies
Hibernate can return a proxy, a generated subclass of Book, for lazy associations and getReference(). Two consequences follow. First, an equals that checks getClass() == o.getClass() says a proxy and a real Book with the same id are different, so we use instanceof, or Hibernate.getClass(o) when exact class matters in an inheritance hierarchy. Second, the fields of an uninitialized proxy are not filled; only its methods load data. That is why the code above reads other.getIsbn() and other.getId() instead of other.isbn or other.id.
6Why Records and Lombok @Data Do Not Fit
Java records cannot be entities. JPA needs a non-final class with a no-argument constructor whose state Hibernate can set and change, while records are final and immutable. Records are excellent as DTO projections, and Hibernate 6.2 and later can map them as embeddables, but not as entities.
Lombok's @Data generates equals and hashCode over all fields. For an entity, that includes the generated id, so the persist problem returns, and mutable fields, so the hash code changes on every setter. It also includes associations, so comparing two books may trigger lazy loading, and with bidirectional associations equals and toString can call each other in a cycle until a StackOverflowError. If we use Lombok on entities, we use @Getter and @Setter and write equals and hashCode by hand as above.
7Follow-up questions
Does Hibernate need equals and hashCode at all?
Within one persistence context, Hibernate guarantees that one row is one Java object, so the default identity-based equals works there. We need our own when entities are put in Sets that span sessions, when detached and managed copies are compared, or when composite ids and embeddables are used, which must always implement both.
Can we assign UUIDs in the constructor and use them for equality?
Yes. An application-assigned UUID is known from creation and never changes, so it behaves like an immutable natural id for equality. With Spring Data, remember that a non-null id makes save() call merge for new entities unless the entity implements Persistable or has a version field.
8Conclusion
In this answer, we saw that equality based on a generated id breaks a HashSet twice: all new entities are equal while their ids are null, and the hash code changes after persist. An immutable natural id assigned at creation gives stable equals and hashCode; without one, we use the id with null treated as unequal and a constant hashCode. We compare with instanceof and getters because of proxies, and we keep records and Lombok's @Data equality away from entities.
Open with
The problem with the generated id is that it is null until the entity is persisted. If equals and hashCode use it, two things break with a Set of Book.
Then, if they want more
Before persist, every new book has a null id, so they are all equal and the set refuses the second one. And after persist the hash code changes, from the hash of null to the hash of the new id, so a book that was added before saving sits in the wrong bucket and contains returns false.
In a mapped collection that leads to elements that cannot be removed or duplicated rows after a merge. My first choice is a natural id that is set in the constructor and never changes, like the ISBN, mapped with NaturalId and updatable false. Then equality is stable before and after persist and across sessions.
If there is no natural key, I use the id in equals, but only when it is not null, so new entities are never equal to each other, and a constant hashCode for the class, like Book.class.hashCode, so it cannot change. That puts all books in one bucket, which is fine for the size of entity collections.
Two more details: because of Hibernate proxies, I use instanceof rather than comparing getClass, and I read values through getters, since proxy fields are not initialized. And records cannot be entities, while Lombok's Data generates equality over all fields, including the id, mutable fields and lazy associations, which is wrong for entities.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Hibernate 6
- 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 "Should equals and hashCode of a JPA entity use the generated id or a natural id? Discuss...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/9faaf5040a/