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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
