how to unproxy a hibernate object

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;
}

Nowadays Hibernate has dedicated method for that: org.hibernate.Hibernate#unproxy(java.lang.Object)


The solution using the HibernateProxy and the getImplementationMethod is correct.

However, I assume you're running into this because your collection is defined as an interface, and hibernate is presenting proxies to the interface.

This leads to the design question, of why have the "if" with the "instanceof" instead of using a interface method to do what you need.

So your loop becomes:

for(B nextB : nextA.getBAssociations() {
    nextB.doSomething();
}

That way, hibernate would delegate the call to "doSomething()" to the actual implementation object, and you'd never know the difference.

Tags:

Java

Hibernate