Entity equality
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
write equals/hashCode that survive the lifecycle.
Planned topics
- Default
equalscompares memory identity; two loads in different transactions are different objects. - Using all fields (as Lombok
@Datadoes) breaks when fields change and can load lazy relations. - The generated id is
nullbefore saving, so id-basedhashCodechanges afterpersistif the entity is in aHashSet. - Safe options: a stable business key (such as SKU) or the id-based pattern with a constant
hashCode. - Never use
@Dataon entities.
Draft outline details
Demonstration
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Product other)) return false;
return id != null && id.equals(other.id);
}
@Override public int hashCode() { return getClass().hashCode(); }Check your understanding
Why is @Data risky on an entity?
Show answer
Its equals/hashCode use all fields, which change and may trigger lazy loading.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.