A generated id is null before persist, so an entity put in a HashSet before saving becomes unfindable afterwards.
@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); }
}
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.
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