Sub topic 15
Implementing equals and hashCode for entities
This chapter assumes you know how to map an entity with an @Id, and that you understand the persistence context and entity states from earlier chapters. It explains why default Java equality is a poor fit for JPA entities. It then shows a safe equals and hashCode implementation.
Why equality needs thought
Java's default equals compares object references. Inside one persistence context that is usually fine, because the context returns the same instance for the same row. Problems start when you compare objects across contexts, or when you keep entities in a HashSet or use them as HashMap keys.
Two common implementations cause trouble:
- Using the generated
idinhashCode. The id isnulluntil the entity is persisted. The hash code changes aftersave, and an entity already stored in aHashSetcan no longer be found. - Using all fields, as many IDE generators do. Mutable fields change the hash code. Lazy associations can trigger extra selects or a
LazyInitializationException.
Option 1: a business key
If the entity has a natural identifier that is unique and does not change, such as an ISBN, base equality on it.
import jakarta.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "isbn_books")
public class IsbnBook {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true, updatable = false)
private String isbn;
protected IsbnBook() {
}
public IsbnBook(String isbn) {
this.isbn = isbn;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof IsbnBook other)) return false;
return Objects.equals(isbn, other.isbn);
}
@Override
public int hashCode() {
return Objects.hash(isbn);
}
}The instanceof check, instead of getClass(), matters. Hibernate may hand you a lazy proxy that is a subclass of your entity. A getClass() comparison would then report two views of the same row as different.
Option 2: the generated id
Many entities have no natural key. In that case, compare by id only when it is set, and return a constant hash code.
import jakarta.persistence.*;
@Entity
@Table(name = "notes")
public class Note {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String text;
protected Note() {
}
public Note(String text) {
this.text = text;
}
public Long getId() { return id; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Note other)) return false;
return id != null && id.equals(other.id);
}
@Override
public int hashCode() {
return Note.class.hashCode();
}
}A new entity with a null id equals only itself. Once it has an id, two instances with the same id are equal. The constant hash code stays stable across the save. The cost is that all Note objects land in one hash bucket. This is acceptable for the small collections that associations normally hold.
Choosing
| Approach | Stable before save | Needs natural key | Hash spread |
|---|---|---|---|
| Business key | Yes | Yes | Good |
| Generated id with constant hash | Yes | No | Poor |
| All fields | No | No | Good |
Exercise
Why does hashCode built from a generated Long id break a HashSet when you add an entity before calling save?
Show answer
The id is null before saving, so the hash code is computed from null. After save assigns the id, the hash code changes. The set still stores the entity in the old bucket, so lookups with the new hash code fail to find it.