Quick revision
The short answer
The standard would sort types into two kinds and give each one rule. Value types, meaning value objects, DTOs and records, are immutable and get generated equals and hashCode over all fields, ideally by being records. JPA entities get equality by a stable business key, or by ID with care for unsaved entities, usually with a constant hashCode per class, and never include lazy associations or mutable collections. Identity-based types such as services keep Object's methods, every type documents which kind it is, and no hand-written equals is merged without a test, for example with EqualsVerifier.
What to remember
In this answer, we built an equality standard by first classifying types. Value objects and DTOs are immutable, preferably records, with equality over all fields. JPA entities use a stable business key, or a non-null ID with a constant hashCode, and never include lazy associations, mutable collections or framework-managed fields. Identity-based types keep Object's methods and say so in their documentation. Hand-written equals needs an EqualsVerifier test, and static analysis catches the common mistakes.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The standard would sort types into two kinds and give each one rule. Value types, meaning value objects, DTOs and records, are immutable and get generated equals and hashCode over all fields, ideally by being records. JPA entities get equality by a stable business key, or by ID with care for unsaved entities, usually with a constant hashCode per class, and never include lazy associations or mutable collections. Identity-based types such as services keep Object's methods, every type documents which kind it is, and no hand-written equals is merged without a test, for example with EqualsVerifier.
Why this question is asked
Most equality bugs do not come from people who do not know the contract. They come from each team, and sometimes each class, making a different choice: one entity compares IDs, another compares all fields including a lazy collection, a DTO forgets hashCode, and a service accidentally gets equals from Lombok. A written standard turns those choices into one decision made once. Interviewers ask this design question to see whether we can write rules that are short enough to follow and precise enough to enforce. In this answer, we will see why one rule for everything cannot work, then go through the rule for value types, the rule for JPA entities, what must never be part of entity equality, how to document identity-based types, and how to enforce the standard.
1Why One Rule Cannot Cover Every Type
Different kinds of objects mean different things by "the same". Two Money values of 15 euros are the same because their contents match; they are values. Two Customer entities are the same if they represent the same row in the database, even if one has an outdated email address in memory; they have identity that outlives their fields. A PaymentService is just one object doing work, and two instances are never "the same" in any useful sense.
So the standard begins by asking each type which kind it is, and then applies the rule for that kind. The table summarises the whole standard; the following sections explain each row.
| Kind of type | equals and hashCode | Mutability |
|---|---|---|
| Value object, DTO, event | Record, or generated over all fields | Immutable |
| JPA entity with business key | Business key only | Key never changes |
| JPA entity with generated ID only | Non-null ID; constant hashCode per class | ID assigned once |
| Service, repository, controller | Do not override (identity) | Not applicable |
| Any hand-written equals | Must have an EqualsVerifier test | As above |
2Rule for Value Objects and DTOs: Records Over All Fields
For value objects, DTOs, commands and events, equality means same contents, so equals and hashCode should use every field. The simplest way to guarantee that is a record, which generates both methods from all its components and cannot fall out of date when a field is added. Where records do not fit, for example a framework that needs a no-argument constructor, the standard allows IDE- or Lombok-generated methods over all fields, with the class final and the fields final.
Notice the compact constructor. A record's fields are final, but a List field can still point to a mutable list, and then the record's hash code can change. Copying with List.copyOf makes the component unmodifiable, so the value really is a value. The standard should say this explicitly, because it is the one way records quietly break.
3Rule for JPA Entities: A Stable Key
Entities need a key that stays the same for the entity's whole life, including the time before it is saved. The preferred option is a business key: a natural identifier such as an order number or an ISBN, assigned when the object is created and never changed. If an entity only has a database-generated ID, the standard uses that ID with two precautions: an unsaved entity, whose ID is still null, is equal only to itself, and hashCode returns a constant per class so it does not change when the ID is assigned.
Two details here are easy to miss. Hibernate may give us a lazy proxy, a generated subclass of Invoice, so the type check must use instanceof rather than getClass(), and the other object's ID must be read through getId(), because a proxy's own fields are not populated. The constant hashCode puts all invoices in one bucket of a HashSet, which sounds slow, but sets of entities in one association are small, and correctness matters more. Either way, the team writes this rule once, in a shared base class or a documented template, rather than reinventing it per entity.
4What Never Goes Into Entity Equality
The standard should forbid three things in entity equals, hashCode and, for the same reasons, toString. Lazy associations, because reading them triggers a database query, or a LazyInitializationException outside a session. Mutable collections, such as a list of order lines, because they change while the entity sits in sets, and bidirectional associations can recurse until StackOverflowError. And fields managed by the database or the framework, such as a version column or an updated timestamp, because they change on every save.
This is also why the standard forbids Lombok's @Data and @EqualsAndHashCode on entities. Those annotations include every field by default, associations included, which is exactly the opposite of the rule.
5Documenting Identity-Based Types
The remaining kind is types whose equality is identity: Spring beans such as services, repositories and controllers, and stateful objects such as connections or sessions. The rule for them is simple: do not override equals or hashCode. The standard should still make the classification visible, because a reader cannot tell from a class whether identity equality is a decision or an oversight.
A short Javadoc line on each public type, "Value type: equality by all fields" or "Identity type: do not use as a value", is enough. Some teams also use marker annotations such as @ValueObject and @Entity, which static analysis can then check: a @ValueObject that is not a record or final class fails the build.
6Enforcing the Standard
A standard that depends on memory decays. The enforcement part says: no hand-written equals or hashCode is merged without a test, and that test should use EqualsVerifier, a library that checks the whole contract, symmetry, transitivity, null handling and hashCode consistency, against a class in one line.
Records need no test, because the compiler generates the methods, which is one more reason to prefer them. Static analysis covers the rest: missing hashCode, equals without @Override, and == between objects. Together these make the standard something the build checks, not something reviewers must remember.
7Follow-up questions
Why not compare all fields in entities, like value objects?
Because an entity's fields change while it keeps its identity. If equals used the email address, a Customer would stop being equal to itself after an update, and it would be lost in any set holding it. Entity equality must be based on something that never changes: a business key or the ID.
Is a shared BaseEntity class with equals and hashCode a good idea?
It can be, if it implements the ID rule correctly once, with instanceof checks against the concrete entity type and a constant hashCode per class. The risk is that a base class compares entities of different types with the same ID as equal, so its equals must check the concrete class, for example through Hibernate's helper that unwraps proxies.
Should DTOs ever be compared by identity?
Almost never. DTOs carry data across boundaries, are compared in tests, deduplicated and cached, all of which need value equality. Records make value equality the default with no effort, which is why the standard picks them.
8Conclusion
In this answer, we built an equality standard by first classifying types. Value objects and DTOs are immutable, preferably records, with equality over all fields. JPA entities use a stable business key, or a non-null ID with a constant hashCode, and never include lazy associations, mutable collections or framework-managed fields. Identity-based types keep Object's methods and say so in their documentation. Hand-written equals needs an EqualsVerifier test, and static analysis catches the common mistakes.
Open with
I would start the standard by classifying types, because equality means different things for each. For value objects, DTOs, commands and events, equality is by all fields and the type is immutable, so the default is a record; if a record does not fit, generated equals and hashCode over all fields on a final class.
Then, if they want more
I would call out that list fields in records must be copied with List.copyOf, or the value is not really immutable. For JPA entities, equality is by a stable business key if there is one.
If there is only a generated ID, equals compares IDs only when they are not null, using instanceof and getId() so Hibernate proxies work, and hashCode returns a constant per class so it does not change on persist. Entity equality never includes lazy associations, mutable collections or version and timestamp fields, which also means no Lombok @Data on entities.
Services and other identity-based types do not override equals at all, and every public type says in its Javadoc which kind it is. To enforce it, no hand-written equals gets merged without an EqualsVerifier test, records need none, and static analysis flags missing hashCode, missing @Override and reference comparisons.
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 documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
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 "Your organization wants a standard for equals and hashCode across domain models, JPA...": https://scrivio-interview-library.netlify.app/java/object-contracts/e42adb9849/