Scrivio Interview library
DesignAdvanced6 min read · updated 12 November 2026

Set a team-wide convention for entity identity, equality and identifiers so that collection bugs and proxy issues stop recurring. What would it contain?

The convention would choose one identity approach, either a UUID assigned at construction or a generated id with the constant-hashCode pattern, and provide a base class or template that implements equals and hashCode that way. It would ban Lombok @Data and @EqualsAndHashCode on entities, keep associations out of toString, explain how proxies affect getClass comparisons, and back all of it with tests and static checks so the rules are enforced rather than remembered.

Why this question is asked

When the same identity bug appears in three teams in one quarter, the problem is not three careless developers; it is the absence of a shared answer. Each team rediscovers that HashSets lose entities after save, that proxies break equals, and that @Data loops forever, and each fixes it slightly differently. Interviewers ask this design question to see whether we can turn hard-won knowledge into a convention that new joiners follow without reading a blog post first. In this answer, we will list the recurring bugs, choose the identity approach, write the shared code, cover toString and proxies, and set up the checks that keep it in place.

1The Bugs the Convention Must Stop

Three bugs cover most incidents. The first is an id-based hashCode, so an entity added to a set before persist cannot be found after it, because its hash changed when the id arrived. The second is a getClass() comparison in equals, so a Hibernate proxy, a generated subclass standing in for an unloaded entity, is never equal to the real object. The third is Lombok @Data or @EqualsAndHashCode on an entity, which includes associations and mutable fields, giving stack overflows on bidirectional relations, unplanned lazy loading, and hashes that change whenever a field changes.

A good convention removes the decision that leads to each bug, rather than describing the bug and hoping people remember.

Recurring bugs and the rule that removes each
BugTypical symptomRule in the convention
hashCode uses generated identity missing from Set after saveconstant hashCode or UUID from construction
getClass() in equalsproxy not equal to loaded entityinstanceof or effective class, getters only
Lombok @Data on entityStackOverflowError, surprise queriesban @Data and @EqualsAndHashCode on entities
associations in toStringlog line loads the graphtoString lists simple fields only
two new entities equalonly one of two new items saved from a Setnull id is never equal unless same reference

2Choosing One Identity Approach

There are two good approaches, and the convention should choose one as the default so that nobody debates it per entity. The first is an application-assigned UUID, created in the field initializer. The id exists from construction, never changes, and can be used directly in both equals and hashCode. It also lets clients create ids offline and makes merging data from several databases easier. The cost is a 16-byte key, and random UUIDs hurt index locality on very large tables; time-ordered UUIDs (version 7) reduce that cost.

The second is a database-generated Long with the constant-hashCode pattern: equals compares ids when both exist, hashCode returns a constant per class. It keeps small keys and familiar sequences, at the cost of a less useful hash, which is fine because entity sets are small.

For a team starting fresh, I would usually choose UUIDv7 for aggregate roots that cross service boundaries and allow sequence ids for internal tables, but the important thing is that the guide states the choice and the reason.

3The Shared Base Class

Code is easier to follow than a document, so the convention ships a small @MappedSuperclass that implements the chosen pattern once. Entities extend it and write no identity methods of their own.

Java
@MappedSuperclass
public abstract class BaseEntity {
@Id @GeneratedValue
private Long id;
public Long getId() { return id; }
@Override
public final boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (effectiveClass(this) != effectiveClass(o)) return false; // proxy-safe class check
Long otherId = ((BaseEntity) o).getId(); // getter, never the field
return getId() != null && getId().equals(otherId);
}
@Override
public final int hashCode() {
return effectiveClass(this).hashCode(); // constant per entity class
}
private static Class<?> effectiveClass(Object o) {
return o instanceof HibernateProxy p
? p.getHibernateLazyInitializer().getPersistentClass() // does not load the entity
: o.getClass();
}
}
new Customer().equals(new Customer()); // false: no ids
customer.equals(em.getReference(Customer.class, customer.getId())); // true

Notice that the methods are final and use getId() rather than the field. When final equals runs on an uninitialized proxy, it runs on the proxy object itself, whose fields are empty, so reading through the intercepted getter is what makes it work. The effective class comes from the proxy's lazy initializer, which knows the real entity class without loading the row. The exact proxy API can differ between Hibernate versions, so the base class is tested against the version we run.

4ToString and Lombok Rules

The guide allows Lombok @Getter and @Setter on entities and forbids @Data, @EqualsAndHashCode and a plain @ToString. If an entity has a toString, it lists only the id and a few simple fields, for example with @ToString(onlyExplicitlyIncluded = true). The reason is spelled out next to the rule: associations in these methods recurse through bidirectional relations and trigger lazy loads, which is how a debug log line once ran three hundred queries in production.

The guide also has a short section on proxies: getReference and lazy @ManyToOne return proxy subclasses, getClass() on them is not the entity class, field access on them returns null, and Hibernate.unproxy returns the real object when one is genuinely needed.

5Enforcing It With Tests and Static Checks

Rules written only in a wiki fade within a year. So each rule gets a check. An ArchUnit test fails the build if any class annotated with @Entity carries @Data or @EqualsAndHashCode, or if an entity overrides equals without extending BaseEntity. A shared contract test, run against every entity class by reflection, creates two new instances and asserts they are not equal, adds one to a HashSet, persists it and asserts the set still contains it, and compares a loaded entity with getReference for the same id.

Java
@ArchTest
static final ArchRule noLombokDataOnEntities =
noClasses().that().areAnnotatedWith(Entity.class)
.should().beAnnotatedWith(lombok.Data.class)
.because("generated equals, hashCode and toString include associations");
// note: Lombok annotations have SOURCE retention by default; if they are not visible
// in bytecode, use a source-level check such as a Checkstyle or PMD rule instead
Step throughHow a new entity meets the convention
  1. Developer writes entityextends BaseEntity, @Getter and @Setter only
  2. Source and ArchUnit checksno @Data, no own equals
  3. Entity contract testset membership across persist, proxy equality
  4. Code review checklisttoString fields, identity choice documented
  5. Merged

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

That last comment is the kind of detail a convention must get right: many Lombok annotations are not present in compiled classes, so the ban may need to live in a source check or in lombok.config, where a team can flag @Data usage as an error. Whichever tool we use, the effect is the same: the mistake fails the build instead of reaching production.

6Follow-up questions

Should we migrate all existing entities to the base class at once?

No. Migrate as part of normal work, starting with entities that appear in sets or have caused incidents. Changing equals semantics can change behaviour in code that relied on the old version, so each migration comes with the contract test for that entity.

Why ban Lombok annotations instead of configuring them with excludes?

Excludes are easy to forget when someone adds a new association, and Lombok's equals still includes mutable fields and the generated id. A ban plus a base class is simpler to review and to check automatically than a set of per-field exclusions.

What if an entity has a natural key such as an ISBN?

The convention can allow an immutable natural key as an alternative identity for equality, with the condition that it is assigned at construction and never updated. That entity then overrides equals and hashCode using the key, and the contract test checks it like any other.

7Conclusion

In this answer, we designed an identity convention that removes the causes of recurring bugs: one chosen approach, UUIDs from construction or generated ids with a constant hash, a shared base class implementing proxy-safe equals and hashCode, a ban on Lombok @Data and @EqualsAndHashCode on entities, toString without associations, a short explanation of proxies, and tests and static checks that make each rule fail the build.

What to say in the interviewAbout 80 seconds aloud

Open with

I would write a short convention with code rather than only prose. First, one identity approach as the default: either application-assigned UUIDs, preferably time-ordered version 7, created at construction so equals and hashCode can use them directly, or database-generated ids with the constant-hashCode pattern.

Then, if they want more

Second, a shared mapped superclass that implements that pattern once: equals checks the same reference, compares effective classes in a proxy-safe way using the proxy's persistent class, and compares ids through getters only when the id is not null; hashCode returns a constant per entity class. Entities extend it and do not write their own.

Third, a ban on Lombok @Data and @EqualsAndHashCode on entities, with @Getter and @Setter allowed, and toString limited to the id and simple fields, never associations, because associations recurse and trigger lazy loads. Fourth, a section on proxies explaining that getClass returns the proxy class and fields are empty, so comparisons must use getters.

And finally enforcement: a source or ArchUnit check that fails the build on banned annotations, and a reflective contract test for every entity that checks set membership across persist and equality with getReference. That way the bugs stop because the build stops them.

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.
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 "Set a team-wide convention for entity identity, equality and identifiers so that...": https://scrivio-interview-library.netlify.app/databases/jpa-relationships/4f87db09bb/