Instanceof fails with Hibernate lazy-loading and entity class hierarchy

Hibernate uses proxied classes for implementing lazy-loading of entities. If you use a class hierarchy with Hibernate and table ter hierarchy inheritance, it may come to the following problem:

Hibernate may return a proxy instead of a normal instance because of lazy loading. This proxy is a subclass of the superclass of your entity but not a subclass of your own subclass. Look at the example:

public class Superclass {...}

public class Subclass1 extends Superclass {...}

public class Subclass2 extends Superclass {...}

If you have an instance of subclass “Subclass1”, anyhow a call of getClass(…) may return a proxy which is not an instance of Subclass1:

// => class Superclass_$$_javassist_87

assertFalse(instanceOfSubclass1 instanceof Subclass1)
instanceOfSubclass1 instanceof Subclass2)

As an alternative the method Hibernate.getClass(…) can be used to determine the specific subclass of the entity:


Short URL for this post:
This entry was posted in Did you know?, Java Persistence and tagged . Bookmark the permalink.