Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

In a code review you see a JPA entity Order whose equals and hashCode use the generated database id. New orders are added to a HashSet<Order> on a parent before the parent is saved. What goes wrong and what would you recommend for entity equality?

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.

Java
@Entity
class Order {
@Id @GeneratedValue Long id;
@Override public boolean equals(Object o) {
return o instanceof Order other && Objects.equals(id, other.id);
}
@Override public int hashCode() { return Objects.hashCode(id); }
}
Customer c = new Customer();
c.getOrders().add(new Order()); // id null, hash 0
c.getOrders().add(new Order()); // id null: equals() says it is the same order
System.out.println(c.getOrders().size()); // 1 the second order was silently dropped
customerRepository.save(c); // cascade persist assigns id 101
Order o = c.getOrders().iterator().next();
System.out.println(c.getOrders().contains(o)); // false: hash is now 101's, node was stored under 0
One Order through its life cycle
MomentidhashCode()Set can find it?
new Order(), added to setnull0yes, stored under hash 0
second new Order() addednull0treated as equal: not added
after save or flush101101no: node still holds hash 0
loaded later in a new session101101yes, 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.

Java
@Entity
class Order {
@Id @GeneratedValue Long id;
@NaturalId @Column(nullable = false, updatable = false)
private String orderNumber; // set in the constructor, never changed
protected Order() { } // for JPA
Order(String orderNumber) { this.orderNumber = orderNumber; }
@Override public boolean equals(Object o) {
return this == o || (o instanceof Order other && orderNumber.equals(other.orderNumber));
}
@Override public int hashCode() { return orderNumber.hashCode(); }
}

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.

Java
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Order other)) return false; // instanceof also accepts Hibernate proxies
return id != null && id.equals(other.getId()); // two new orders are never equal
}
@Override public int hashCode() { return Order.class.hashCode(); } // constant: never moves bucket

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.

Java
@Entity
class Order {
@Id private UUID id = UUID.randomUUID(); // known from construction, never changes
@Version private Long version; // lets Spring Data tell new from existing
@Override public boolean equals(Object o) { return o instanceof Order other && id.equals(other.getId()); }
@Override public int hashCode() { return id.hashCode(); }
}
Choosing an entity equality pattern
PatternStable across save?Main cost
equals/hashCode on generated idnothe bug in this review
Business key (@NaturalId)yes, if the key never changesneeds a truly immutable key
id equals + constant hashCodeyesone bucket per set: slow for huge sets
UUID assigned at constructionyesbigger, less index-friendly keys
No override (identity)yes, within one sessiondifferent 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.

What to say in the interviewAbout 100 seconds aloud

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.
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/