Video in progress

Strong Middle 🧭 Design patterns

What problems does a Hibernate lazy proxy cause with `equals`, `getClass()` and `instanceof`?

A lazy reference isn't the entity itself but a subclass of it generated by Hibernate. getClass() returns the proxy class, so an equals written with getClass() != o.getClass() says the same row is not equal to itself; in a hierarchy, instanceof misleads you too.

📖 Answer

If order.getCustomer() is lazy, you don't get a Customer, you get a Customer$HibernateProxy$... object. It hasn't gone to the database yet and only knows its id. This is the classic use of the proxy pattern: a virtual proxy.

An equals generated by the IDE:

if (o == null || getClass() != o.getClass()) return false;

When a proxy is compared with the real entity, the classes differ and you get false. In a Set<Customer>, the same customer shows up twice.

The second trap is direct field access: this.id.equals(other.id). A proxy's fields are empty (null); values are loaded only through a getter. So inside equals, write other.getId().

The third is inheritance. If a Payment is loaded lazily, the proxy extends Payment, not CardPayment. payment instanceof CardPayment is false even when the real object is a CardPayment. The fix: Hibernate.unproxy(payment) or a polymorphic method.

The equals used in practice:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Customer other)) return false;
    return getId() != null && getId().equals(other.getId());
}
@Override
public int hashCode() { return Customer.class.hashCode(); }

hashCode is constant because the id appears only after persist, and an object inside a HashSet must not get lost.