Skip to content
Ameen Abozaid
Planned lessonJNR-028-L06

Entity equality

  • Lesson 6 of 8
  • Junior
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 equals compares memory identity; two loads in different transactions are different objects.
  • Using all fields (as Lombok @Data does) breaks when fields change and can load lazy relations.
  • The generated id is null before saving, so id-based hashCode changes after persist if the entity is in a HashSet.
  • Safe options: a stable business key (such as SKU) or the id-based pattern with a constant hashCode.
  • Never use @Data on entities.
Draft outline details

Demonstration

java
@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.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.