Sub topic 15
Implementing equals and hashCode for entities
This chapter assumes you can map an entity with @Entity and @Id. It also assumes you know the persistence context and entity states from the earlier chapters, and that you know how equals and hashCode behave in HashSet and HashMap.
Why entities need a deliberate choice
Java's default equals compares object references. Two Book objects loaded in the same persistence context for the same row are the same instance, so the default works there. Hibernate guarantees one managed instance per identifier within one persistence context.
The default breaks when instances from different contexts meet. This happens when you:
- keep entities in a
Setacross transactions, - compare a detached entity with a freshly loaded one,
- remove an entity from a collection by value,
- compare a lazy proxy with a real instance.
Overriding equals and hashCode fixes some of these problems and can create new ones. The hard part is that an entity's state changes over its lifetime. The id is null until the entity is persisted (with GenerationType.IDENTITY, until the insert runs). Other fields change through updates.
The contract you must keep
- If
a.equals(b), thena.hashCode() == b.hashCode(). hashCodemust not change while the object sits in a hash-based collection.equalsis reflexive, symmetric and transitive.
A hashCode computed from a generated id violates the second rule. The entity goes into a HashSet with id null, gets an id on persist, and then the set can no longer find it.
import java.util.HashSet;
import java.util.Set;
public class BrokenHashDemo {
static class Item {
Long id;
@Override
public boolean equals(Object o) {
return o instanceof Item other && id != null && id.equals(other.id);
}
@Override
public int hashCode() {
return id == null ? 0 : id.hashCode(); // changes when id is assigned
}
}
public static void main(String[] args) {
Set<Item> set = new HashSet<>();
Item item = new Item();
set.add(item); // stored in the bucket for hash 0
item.id = 42L; // simulates the id assigned on persist
System.out.println(set.contains(item)); // prints false
}
}The item is in the set, but contains looks in the bucket for the new hash and finds nothing.
Three strategies
| Strategy | `equals` uses | `hashCode` | Works before persist | Main risk |
|---|---|---|---|---|
| Default identity | Reference | Identity hash | Yes | Fails across persistence contexts |
| Business key | An immutable natural key such as an ISBN or SKU | Hash of that key | Yes | Needs a truly stable, unique key |
| Id-based | The generated id, only if not `null` | Constant | Partly | Transient instances are never equal to each other |
Business key
A business key is an attribute that identifies the real-world thing and never changes, such as an ISBN, a SKU or a username. It is available before the first save, so it behaves the same in every entity state.
import jakarta.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true, updatable = false, length = 40)
private String sku;
private String name;
protected Product() {
}
public Product(String sku, String name) {
this.sku = Objects.requireNonNull(sku);
this.name = name;
}
public String getSku() { return sku; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Product other)) return false;
return sku.equals(other.getSku());
}
@Override
public int hashCode() {
return sku.hashCode();
}
}Three details matter here:
updatable = falsestops Hibernate from writing changes to the column, and the class has no setter for it.unique = truemakes the database enforce the assumption.equalscallsother.getSku()rather than readingother.sku. On a lazy proxy the field is not initialized, but the getter forwards to the real object.
Id-based equality
Many entities have no natural key. For these, the commonly recommended pattern compares ids only when both are set and uses a hash code that never changes:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Book other)) return false;
return id != null && id.equals(other.getId());
}
@Override
public int hashCode() {
return Book.class.hashCode();
}Add these two methods to the Book entity from the associations chapter. Reading each part:
this == omakes an instance equal to itself even when its id isnull.id != nullmeans two different transient books are never equal, which is correct because they are different rows-to-be.- The constant hash code stays the same through every state change. All books land in one bucket, so lookups in large sets degrade to a linear scan. Entity collections are usually small, so this rarely matters. If you hold thousands of entities in one
Set, prefer a business key.
Proxies and getClass
Lazy @ManyToOne associations are often filled with a Hibernate proxy, which is a generated subclass of your entity. If you write getClass() != o.getClass() in equals, a proxy never equals the real instance, even for the same row. Use instanceof instead, and call getters on the other object.
instanceof assumes the entity class hierarchy does not redefine equality in subclasses. If you use entity inheritance, define equals once in the root entity and do not override it below.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Entity "disappears" from a `HashSet` after `save` | `hashCode` depends on a generated id | Use a constant hash code or a business key |
| `LazyInitializationException` inside `hashCode` | Hash includes a lazy collection or association | Use only the key attributes |
| `StackOverflowError` | Both sides of a bidirectional association are in `equals` or `hashCode` | Never include associations |
| Proxy not equal to the loaded entity | `getClass()` comparison or direct field access | Use `instanceof` and getters |
| Two new entities treated as one in a `Set` | `equals` returns true when both ids are `null` | Require `id != null` |
| Business key duplicates rejected late | No unique constraint | Add `unique = true` and a database constraint |
Verifying the behavior
A plain JUnit test needs no Spring context for the business-key version:
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
class ProductEqualityTest {
@Test
void productsWithSameSkuAreEqualAndDeduplicated() {
Product a = new Product("SKU-1", "Lamp");
Product b = new Product("SKU-1", "Lamp, renamed");
Set<Product> set = new HashSet<>();
set.add(a);
set.add(b);
assertThat(a).isEqualTo(b);
assertThat(set).hasSize(1);
}
}To test the id-based version, use @DataJpaTest. Save an entity, call entityManager.flush() and entityManager.clear(), then load it again. Assert that the loaded instance equals the one you saved. The clear forces a new instance, which is the situation where default equality fails.
Decision criteria
- Choose a business key when a stable, unique, never-null attribute exists and you control its assignment.
- Choose id-based equality for entities with surrogate keys only, and accept that unsaved entities are not equal to each other.
- Choose the default when entities never leave one persistence context and never go into hash-based collections. This is often true for simple Spring Data applications that use
Listand map entities to DTOs before returning them.
Exercise
An entity defines hashCode() as Objects.hash(id) and uses GenerationType.IDENTITY. You add a new instance to a HashSet, call repository.save(entity), and then set.contains(entity) returns false. Explain why, and give two ways to fix it.
Show answer
Before save, the id is null, so the entity is stored in the bucket for Objects.hash(null). The insert assigns an id, which changes the hash code, so contains looks in a different bucket and does not find the entity. Fix it by making hashCode independent of the generated id, either with a constant such as Book.class.hashCode() together with an equals that compares non-null ids, or with a business key such as a unique, non-updatable SKU. You can also avoid adding the entity to the set until after it is saved, but that leaves the trap in place.
Exercise
Why should equals for an entity call other.getSku() instead of reading other.sku, and why should it use instanceof instead of getClass()?
Show answer
The other object may be a Hibernate lazy proxy, which is a generated subclass whose own fields are not initialized. Calling the getter forwards to the real target and returns the actual value. A getClass() comparison would treat the proxy subclass as a different type from the entity, so a proxy and the real instance for the same row would never be equal. instanceof accepts the subclass.