Video in progress

Strong Junior 🐻 Hibernate and JPA

How should you write equals() and hashCode() for an entity, and what's the problem with a generated id?

A generated id is null until persist and gets a value afterward. If hashCode is computed from the id, the hash changes after the object has been added to a HashSet, and you can no longer find it in the set. Usually you use a natural key, or write equals based on the id and a constant hashCode.

📖 Answer

Here is a case that shows the problem:

Set<Tag> tags = new HashSet<>();
Tag t = new Tag("java");       // id = null
tags.add(t);                   // the hash was computed from a null id
em.persist(t); em.flush();     // id = 42
tags.contains(t);              // false! the hash is in a different bucket

A widely used correct version:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Tag other)) return false;
    return id != null && id.equals(other.getId());
}

@Override
public int hashCode() {
    return Tag.class.hashCode(); // always the same, even if the id changes or it's a proxy
}

Two new objects (without ids) are not equal, and saved ones are compared by id. It's not an accident that hashCode uses the explicit Tag.class and not getClass(): a proxy has a different class, and getClass().hashCode() would give equal objects different hashes. A constant hashCode is inefficient in a big HashSet, but entity collections are usually small.

Other options:

  • if there is a unique business key (email, ISBN), write equals/hashCode on that; in Hibernate you can mark it with @NaturalId;
  • generate the id in the application (a UUID in the constructor): then the id exists from the start and the problem goes away.

Two more notes: use instanceof, not getClass() ==, because a Hibernate proxy is a subclass. And access fields through the getter, not directly, because the fields of a proxy are empty.