Hibernate: equals and hashCode on an entity must not use the id

A generated id is null before persist, so an entity put in a HashSet before saving becomes unfindable afterwards.

Code
@Entity
class Order {
    @Id @GeneratedValue Long id;
    @Column(unique = true) String reference;   // a real business key

    @Override public boolean equals(Object o) {
        return o instanceof Order other && Objects.equals(reference, other.reference);
    }
    @Override public int hashCode() { return Objects.hash(reference); }
}
Output
With an id-based hashCode:
set.add(order);   // hashCode from id = null
repo.save(order); // id becomes 42, hashCode changes
set.contains(order) -> false, and the object leaks in the set.
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-11