Hard👤 8-15 years 1 min read

How should equals() and hashCode() be implemented for JPA/Hibernate entities?

Asked inDeloitteAmazonCognizantAccenture
#equals#hashcode#jpa#hibernate#orm#identity
Report issue

⚡ Short Answer

Don't use the auto-generated DB id (it's null before persist) or all mutable fields. Use a stable business key, or a UUID assigned at construction. Inconsistent equals/hashCode breaks Sets and causes duplicates after merge/persist.

Coffee Chat Question

Concept Made Simple

How should equals() and hashCode() be implemented for JPA/Hibernate entities?

🧠Mind Map Answer

Remember It Faster

The trap: a new entity has id == null. If equals/hashCode use id, the object's hash changes once persisted — so it's lost in any HashSet it was added to before saving.

All fieldsbreaks on mutation / lazy proxies
DB idnull pre-persist → hash changes
Beststable business key or app-assigned UUID

⌨️Hands-on Keyboard

Learn by Doing

java
@Entity class Customer {
    @Id private final UUID id = UUID.randomUUID(); // assigned at creation
    @Override public boolean equals(Object o) {
        return o instanceof Customer c && id.equals(c.id);
    }
    @Override public int hashCode() { return id.hashCode(); }
}

🔥What If?

Think Beyond the Expected

Why can equals fail on a lazily-loaded entity inside a Set?

Hibernate may hand you a proxy subclass, so getClass()-based equals returns false against the real class. Use instanceof (not getClass()) and compare the id field directly — proxies still resolve the id.

😂Real World

Duplicate rows in a @OneToMany Set, or entities 'disappearing' from a HashSet after save, almost always trace to id-based equals/hashCode on entities whose id is generated by the database.

🎯Interviewer's Expectation

Keywords they're listening for:

null id before persisthash must be stablebusiness key / app-assigned UUIDinstanceof not getClass (proxies)Set semantics

⚠️Common Mistakes

  • equals/hashCode based on a DB-generated id
  • Using all mutable fields in equals
  • getClass() comparison failing against lazy proxies

Best Practices

  • Assign a UUID/business key at construction for identity
  • Use instanceof in equals to tolerate proxies
  • Keep hashCode stable across the entity's lifecycle

🔁Follow-up Questions

  • 1Why prefer app-assigned UUIDs over DB-generated ids for identity?
  • 2How do Hibernate proxies affect equals/getClass?
  • 3When is it OK to rely on default Object identity?

🧩Related Technologies

JPA/HibernateUUIDLombok @EqualsAndHashCode(of=...)Spring Data

Continue Learning with AI

Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly — AI is your learning companion, not a shortcut.

Plain-language foundations

I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner.

Topic: OOP (Core Java)
Interview question: "How should equals() and hashCode() be implemented for JPA/Hibernate entities?"

Please:
1. Explain the core idea in simple, plain language, using an everyday analogy.
2. Define any technical terms you use.
3. Walk through one small, concrete example.
4. Finish with a single sentence I can easily remember.

Keep the tone friendly and assume I'm new to this topic.
Open inChatGPTGeminiClaude

Was this answer helpful?

Support our platform by exploring our recommended products.

As an Amazon affiliate, purchases through these links may earn us a small commission — at no extra cost to you. It helps keep Full Stack Interview Guru free.

Related Questions