Video in progress
How do you choose an equals/hashCode strategy for JPA entities kept in a HashSet and compared across services?
A hashCode based on the generated id changes after the entity is saved and breaks the HashSet. I choose a stable business key or a UUID created in the application; if that isn't possible, a constant per-class hashCode and equals by id.
📖 Answer
The problem:
Set<OrderLine> lines = new HashSet<>();
OrderLine line = new OrderLine(...); // id == null
lines.add(line);
em.persist(line); // id = 42, hashCode changed
lines.contains(line); // false
An entity's equality must stay stable throughout its lifecycle: transient, managed, detached, and reloaded from another session.
The options:
-
A natural business key (ISBN,
email,orderNumber). The cleanest, if the key is truly immutable and unique. In practice many "unique" fields change later (even email). -
A UUID created in the application: assigned in the constructor, either the same as the DB id or a separate column.
equals/hashCodeare based on it. It is stable even before saving. The cost is index size; time-ordered variants like UUIDv7 are better for the B-tree. -
A generated
idand a constanthashCode:
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof OrderLine other)) return false;
return id != null && id.equals(other.getId());
}
@Override public int hashCode() { return getClass().hashCode(); }
It works correctly, but in big collections all elements land in one bucket. Entity collections are usually small, so this is acceptable.
Don't forget Hibernate proxies either: getClass() may return the proxy class, so instanceof and reading fields through getters are safer.
Between services, you shouldn't compare entities at all. A DTO goes out, and equality there is by global identifier only. At the organization level, I set the rule "every aggregate has a global ID". That also simplifies deduplication, idempotency and matching up events.
Sign up to mark studied questions and save your progress.