May 22, 2009 1
The Trouble with Proxies: Hibernate or DataNucleus
Hibernate and DataNucleus (JDO2) are arguably the two most substantial persistence frameworks in the open source ecosystem. I have worked with DataNucleus quite a bit on the side, and I am now finding an opportunity to use Hibernate during my day job.
I have now spent enough time using Hibernate to appreciate the approach that DataNucleus takes using bytecode enhancement in comparison to Hibernate’s proxies. Essentially, I am finding myself having to appease Hibernate’s view of the world in unexpected ways where I would like to leave my code alone. Two problem cases have come up so far that I would not have encountered with DataNucleus: using instanceof with type hierarchies and implementing equals. In both of these case, bytecode enhancement would leave my Java code to work just as I expected; but instead, I have to deal with an extra layer of indirection where I was expecting to deal directly with my objects.
Type hierarchies and instanceof
Lets say that I have the following type hierarchy:
public interface Transformer { ... } public interface Autobot extends Transformer { ... } public interface Decepticon extends Transformer { ... }
Obviously, there are times that I may be given an instance of type Transformer where I want to distinguish between an Autobot and a Decepticon using instanceof. However, if I am persisting these instances with Hibernate, and I receive a proxy to the persisted entity, I cannot use instanceof to determine the type of the instance I am dealing with. In Hibernate, the entity instance could well be an Autobot, but the returned proxy to the entity will implement both the Autobot and the Decepticon types.
In order to determine the instance type I am dealing with, I have to either unwrap the proxy or turn off lazy loading. Both of these are undesirable solutions. Unwrapping the proxy adds extra persistence operations outside of the persistence tier of your application, which violates a clean separation of concerns. And of course, there is a performance hit for turning off lazy loading. I wouldn’t have to use either of these undesirable solutions with DataNucleus.
Read the rest of this entry »
Recent Comments