Scrivio Interview library
ConceptIntermediate7 min read · updated 12 November 2026

Write the recommended equals and hashCode for a JPA entity with a generated Long id, and explain why Lombok's default does not work with Hibernate proxies.

The recommended equals returns true for the same instance, returns false for null or when the effective classes differ after unwrapping Hibernate proxies, and otherwise compares ids only when the id is not null; hashCode returns a constant per class so it does not change when the id is assigned at persist. Lombok's default fails because it compares all fields, its hashCode changes with them, and with Hibernate proxies it either reads uninitialised fields, which are null in the proxy subclass, or forces the proxy to load through getters. A natural business key that never changes, such as an ISBN, is a good alternative to the id.

Why this question is asked

Entity equality looks like a small detail until it breaks: a Set of entities loses members after a save, a merged entity is not recognised as the one already in a collection, or a lazy proxy compares unequal to the real object it stands for. Interviewers ask this question because getting it right requires knowing what an entity's identity is, when Hibernate assigns ids, and what a Hibernate proxy really is. In this answer, we will recap entity identity and proxies, see why Lombok's default fails, write the recommended equals and hashCode, look at natural keys, and finish with how to use Lombok here if we still want to.

1A Quick Recap: Entity Identity and Hibernate Proxies

An entity represents a row, and two entity objects are "the same" when they represent the same row, which is what the primary key identifies. With a generated Long id, though, a new entity has no id until it is persisted; at that moment Hibernate assigns it. So identity is unknown for part of the object's life, and equals and hashCode must cope with that.

A Hibernate proxy is a subclass of our entity that Hibernate generates at run time to stand in for an object it has not loaded yet, for example the target of a lazy @ManyToOne or the result of getReferenceById(). The proxy knows its id, but its own fields are not filled in; when we call a method on it, it loads the real object and forwards the call. So a proxy's class is not exactly Book.class but a generated subclass, and reading its fields directly gives nulls.

2Why Lombok's Default Does Not Work

Lombok's generated equals, with @Data or plain @EqualsAndHashCode, checks the type with instanceof and canEqual and then compares every field. It uses getters when they exist and reads fields directly otherwise. Both behaviours go wrong with proxies. Reading fields directly on a proxy gives null for everything except what Hibernate set, so a proxy never equals the real object. Using getters forces the proxy to load from the database during an equals call, which costs a query and throws LazyInitializationException outside a session.

Even without proxies, comparing every field is the wrong meaning of identity: the same row with a changed title compares unequal. And the generated hashCode includes the id and mutable fields, so it changes at persist and on every edit.

Java
@Entity @Data
public class Book { @Id @GeneratedValue private Long id; private String title; }
Book b = new Book(); b.setTitle("Dune");
Set<Book> books = new HashSet<>(Set.of(b));
em.persist(b); // id assigned, hashCode changes
System.out.println(books.contains(b)); // false
Book ref = em.getReference(Book.class, b.getId()); // a proxy, fields not loaded
// ref.equals(b) either loads the row through getters, or compares nulls if fields are read directly

3The Recommended equals and hashCode

Here is the pattern widely recommended for Hibernate entities. It uses the effective class, unwrapping proxies, so that a proxy and a loaded object of the same entity can be equal, and it compares only ids, read through getId(), which a proxy answers without loading.

Java
@Entity
public class Book {
@Id @GeneratedValue
private Long id;
private String title;
public Long getId() { return id; }
@Override
public final boolean equals(Object o) {
if (this == o) return true; // same instance
if (o == null) return false;
Class<?> oClass = o instanceof HibernateProxy p
? p.getHibernateLazyInitializer().getPersistentClass() : o.getClass();
Class<?> thisClass = this instanceof HibernateProxy p
? p.getHibernateLazyInitializer().getPersistentClass() : this.getClass();
if (thisClass != oClass) return false; // different entity types
Book other = (Book) o;
return getId() != null && Objects.equals(getId(), other.getId()); // new entities are never equal
}
@Override
public final int hashCode() {
return this instanceof HibernateProxy p
? p.getHibernateLazyInitializer().getPersistentClass().hashCode()
: getClass().hashCode(); // constant per entity class
}
}
// book.equals(em.getReference(Book.class, book.getId())) -> true, without loading the row
Step throughRecommended entity equals
  1. Same instance?
    YestrueNoIs o null?
  2. Is o null?
    YesfalseNoCompare effective classes
  3. Same effective class?proxies unwrapped to the entity class
    YesCompare idsNofalse
  4. Is this id null?not persisted yet
    Yesfalse: unknown identityNoid equals other.getId()

4 steps in order. Play them, or step through them one at a time.

Notice the reasons behind each line. The null-id check means two new, unsaved books are not equal to each other, even if all their fields match, because we cannot know they are the same row. The constant hashCode means the hash does not change when persist assigns the id, so a book added to a Set before saving is still found afterwards; all books share one bucket, which is acceptable for the small collections entities usually live in. The methods are final so that the proxy subclass uses this logic rather than intercepting it. HibernateProxy is Hibernate's interface for proxies; check your Hibernate version for helper methods that do the same unwrapping.

4Natural Business Keys

Some entities have a natural key: a value that identifies the thing in the real world and never changes, such as a book's ISBN or a country's ISO code. If the key is assigned when the object is created and is immutable, equals and hashCode can simply use it. The hashCode can then be based on the key instead of a constant, because it is known from the start and never changes.

Java
@Entity
public class Book {
@Id @GeneratedValue private Long id;
@NaturalId @Column(nullable = false, unique = true, updatable = false)
private String isbn;
@Override public final boolean equals(Object o) {
return o instanceof Book b && isbn.equals(b.getIsbn()); // getIsbn(): proxy-safe
}
@Override public final int hashCode() { return isbn.hashCode(); }
}

The catch is the word "never". Email addresses and user names look like natural keys but change, and a key that changes brings back every problem we just solved.

5If You Still Use Lombok Here

If a team wants Lombok on entities, the least harmful form is @EqualsAndHashCode(onlyExplicitlyIncluded = true) with @EqualsAndHashCode.Include only on an immutable natural key, assigned in the constructor. For a generated id, Lombok's version still has a hashCode that changes from null to the real id, and its class check does not unwrap proxies, so the hand-written version above is safer. Many teams simply write these two methods by hand for every entity, sometimes in a mapped superclass, and keep Lombok for getters.

6Follow-up questions

What happens to a HashSet of new entities after they are persisted with Lombok's default hashCode?

The entities were placed in buckets according to hash codes computed while their ids were null. After persist, each id is set and each hashCode changes, but the entities stay in their old buckets. contains() and remove() then look in the wrong buckets and fail, and adding an entity again creates a duplicate. Worse, before persisting, two new entities with identical field values were equal under Lombok's rules, so the set may have kept only one of them. With the recommended pattern, new entities are never equal to each other and the constant hashCode never changes.

Why use getId() instead of other.id?

Because other may be a proxy. Hibernate answers getId() on a proxy from the identifier it already holds, without loading the row, while the proxy's own id field may be empty.

Why not compare with instanceof?

instanceof accepts subclasses, and a proxy is a subclass, so it can work, but in an entity hierarchy it would let a parent and a child entity compare equal. Comparing the effective classes after unwrapping is precise for both cases.

7Conclusion

In this answer, we saw that an entity's identity is its row, unknown until the id is generated, and that Hibernate proxies are subclasses with unfilled fields. Lombok's default compares all fields, changes its hashCode with them and either reads null proxy fields or forces loading. The recommended equals checks the same instance, null and the effective class after unwrapping proxies, then compares ids only when the id is not null; hashCode is a constant per class. A truly immutable natural key, like an ISBN, is a good alternative, and if Lombok is used at all, it should include only that key.

What to say in the interviewAbout 90 seconds aloud

Open with

An entity's identity is the row it represents, so equality should be about the primary key, but a generated id is null until persist. That shapes the pattern. equals returns true for the same instance, false for null, then compares the effective classes, unwrapping a HibernateProxy to its persistent class, because a proxy is a generated subclass.

Then, if they want more

If the classes differ it returns false, and otherwise it returns true only if this id is not null and equals the other's id, read through getId(), which a proxy answers without loading.

So two new unsaved entities are never equal. hashCode returns a constant per class, like getClass().hashCode() with the same proxy unwrapping, so it does not change when the id is assigned at persist; entities in a Set stay findable. I make both methods final. Lombok's default does not fit.

It compares all fields, so the same row with a changed field is unequal, and its hashCode changes at persist. With proxies it either reads fields directly, which are null in the proxy, or calls getters, which forces loading and can throw LazyInitializationException.

An alternative is a natural business key that never changes, like an ISBN, annotated @NaturalId; then equals and hashCode can simply use it. If someone insists on Lombok, I would only accept onlyExplicitlyIncluded with the include on such an immutable key.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write the recommended equals and hashCode for a JPA entity with a generated Long id, and...": https://scrivio-interview-library.netlify.app/java/lombok/94a4799420/