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 {...}

@Entity
public class Subclass1 extends Superclass {...}

@Entity
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:

System.out.println(instanceOfSubclass1.getClass())
// => class Superclass_$$_javassist_87

assertFalse(instanceOfSubclass1 instanceof Subclass1)
assertFalse(
instanceOfSubclass1 instanceof Subclass2)
assertTrue(
instanceOfSubclass1.getSuperclass().isCase(Superclass))

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

assertTrue(Hibernate.getClass(instanceOfSubclass1).isCase(Subclass1))
assertFalse(Hibernate.getClass(instanceOfSubclass1).isCase(Subclass2))

Short URL for this post: http://wp.me/p4nxik-bp
This entry was posted in Did you know?, Java Persistence and tagged . Bookmark the permalink.