Friday, August 1, 2008

Extract the original entity from a (Hibernate) CGLIB proxy class

Ed: this is a rewrite of another post that deals with the same problem but with a less technical description.

If you have a polymorphic class structure then when Hibernate instantiates instances of your sub-classes and wraps them in a proxy class, the proxy is actually an instance of the root class in the hierarchy. This introduces some problems because you can no longer rely on instanceof and class casts because they will not work. You can implement a visitor pattern to work around these shortcomings.

The following code shows you how to retrieve the persisted concrete instance of your sub-class from the proxy class. This is useful for those occasions when you want access to the concrete instance, but don't want to implement a full visitor pattern:

if (proxy instanceof HibernateProxy){ 
   return ((HibernateProxy)proxy).getHibernateLazyInitializer().getImplementation(); 

No comments: