Video in progress

Strong Middle 🐻 Hibernate and JPA

How do `getClass()` and `instanceof` checks mislead you when working with a Hibernate proxy?

A lazy @ManyToOne field returns a subclass proxy that Hibernate generated, not the real class. getClass() gives the proxy class, and in an inheritance hierarchy the proxy is created for the parent type, so instanceof CardPayment can come out false.

📖 Answer

People get burned in two places.

1. getClass() inside equals:

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

On one side you have Customer, on the other Customer$HibernateProxy$abc. They're not equal, even if the ids are the same. Use instanceof or Hibernate.getClass(o).

2. Polymorphic associations:

@ManyToOne(fetch = FetchType.LAZY)
private Payment payment;   // Payment is abstract, actually CardPayment

if (order.getPayment() instanceof CardPayment card) { ... } // false!

When Hibernate creates the proxy, it doesn't know the real type (that would take a SELECT), so it creates it as a subclass of Payment. Even after the proxy is initialized, it doesn't become a CardPayment.

Fixes:

  • Hibernate.unproxy(order.getPayment()) returns the real object (loading it if needed);
  • fetch the association with join fetch in that case, and no proxy is created at all;
  • instead of instanceof, use a polymorphic method (payment.describe()), which is also the better design from an OOP point of view;
  • with bytecode enhancement, Hibernate may in some cases give you an object of the right type instead of a proxy.

Calling getId() on a proxy doesn't load it, which is a nice property. But accessing a field directly (other.id) gives null on a proxy, so use the getter inside equals too.