Wednesday, July 4, 2012

Java Hibernate & Proxy


One of the strenghts of  Hibernate is the option for lazy loading. This means that we do not actually load the object from the db, but hibernate creates a proxy object, and only when we actually need the object does it go to the database and get the information.
This helps on performance of the product, but can cause a lot of side effects.
The proxy class is not the actual class, but implemenets all the public methods of the real class and then delegates them to the real class when created.
Some times this is not good enought and you need the actual class and not the proxy.
After searching the internet i have found the following way to get from hibernate the actuall class and not the proxy.

public static <T> T initializeAndUnproxy(T entity) {
    if (entity == null) {
        throw new 
           NullPointerException("Entity passed for initialization is null");
    }

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