Tuesday, March 5, 2013

Hibernate Proxy Cast to Entity Class

When Hibernate returns an entity from the database it isn't actually an instance of that object.  It is a proxy object.  Generally it doesn't really matter because all of the entities methods are created in the proxy, but sometimes when you use an inheritance strategy you are querying via the parent entity but you want the child instance that is returned.

It's tempting to try using instanceof and casting it to the right object type, but because it's a proxy instanceof doesn't work. There is a way to "cast" it to the right object type, but it involves getting the object out of the proxy, and as you can imagine you would lose your Hibernatey-ness.
Or of course you could just query for the child object.

Useful links:

No comments:

Post a Comment