Video in progress
How should you write equals() and hashCode() in a JPA entity?
You have to account for new entities that don't have an id yet and for lazy proxies. The reliable option: compare by id (if id is null — not equal) and use a constant hashCode (for example, the class hash). Comparing all fields or using Lombok @Data gets you bugs.
📖 Answer
What breaks:
- An entity with a
@GeneratedValueid hasid = nullbeforepersist. If hashCode is computed from the id, it changes after the object is added to aHashSet, and the object "gets lost" in the set. - A Hibernate lazy proxy —
Order$HibernateProxy$...— comparing bygetClass()treats the proxy and the real object as different. - Comparing all fields loads lazy collections, and mutable fields break the hash.
- Lombok
@Data/@EqualsAndHashCodegives infinite recursion on bidirectional associations.
This template works:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
return id != null && id.equals(((Product) o).getId());
}
@Override
public int hashCode() {
return Hibernate.getClass(this).hashCode(); // doesn't depend on id — never changes
}
A constant hashCode puts every object into the same "bucket", but entity collections are usually small, so in practice it's not a problem.
If the entity has a natural business key (say isbn or email — immutable and unique), basing equals/hashCode on it is the cleanest option. Another way is to make the id a UUID generated in the constructor, so it exists from the start.
Sign up to mark studied questions and save your progress.