how to unproxy a hibernate object

hibernate, java

Solution

Here's our solution, added to our persistence utils:

public T unproxy(T proxied)
{
    T entity = proxied;
    if (entity instanceof HibernateProxy) {
        Hibernate.initialize(entity);
        entity = (T) ((HibernateProxy) entity)
                  .getHibernateLazyInitializer()
                  .getImplementation();
    }
    return entity;
}

Problem

How can I unproxy a hibernate object, such that polymorphism would be supported? Consider the following example. Classes A and B are two hibernate entities. B has two subtypes C and D. ``` List<A> resultSet = executeSomeHibernateQuery(); for(A nextA : resultSet) { for(B nextB : nextA.getBAssociations() { if(nextB instanceof C) { // do something for C } else if (nextB instanceof D) { // do something for D } } } ``` This code fails to execute either the C or D block, since the B collection has been lazy loaded, and all instances of B are Hibernate proxies. I'd like a way to unproxy each instance. Note: I realize the query can be optimized to eagerly fetch all B's. I'm looking for an alternative.

Original source

Related problems