Java / Lombok Interview questions
Why should you be careful using @EqualsAndHashCode on Hibernate entities with lazy-loaded proxies?
Hibernate sometimes returns a lazy-loading proxy object standing in for the real entity, rather than
the actual entity instance itself — and a proxy's runtime class differs from the real entity's class
(it's a dynamically generated subclass). A naive equals() comparing
this.getClass() == other.getClass(), which is what @EqualsAndHashCode can generate
by default in some configurations, can incorrectly report a real entity and its own proxy as unequal, purely
because their runtime classes differ.
@EqualsAndHashCode(onlyExplicitlyIncluded = true) @Entity public class Product { @Id @EqualsAndHashCode.Include private Long id; // compare by id, ignoring runtime class differences from proxying }
The safer pattern is to base equality on the entity's stable identifier field alone, using
onlyExplicitlyIncluded = true combined with @EqualsAndHashCode.Include on just the
id, and to compare using instanceof rather than exact class equality, avoiding the proxy/class
mismatch entirely.
More Related questions...