Tuesday, March 4, 2014

Hibernate Lazy Load exception and how to load an relationship



Hibernate and lazy loading sucks. Especially in Web Dynpro where we cannot use the Session in View pattern. Therefore there is handy method can load a collection to make sure that a collection is loaded and load it on demand from the service layer

public abstract class GenericDaoBean implements GenericDao

// ....

public void initializeRelationship(T entity, String property) {
        org.hibernate.Session session = getHibernateSession();
        // the lock method adds the entity back into the Entitymanager makes it managed.
        try {
            session.lock(entity, LockMode.NONE);
            Object collectionProxy = getAttributeValue(entity, property);

            if(!Hibernate.isInitialized(collectionProxy))
            {
                Hibernate.initialize(collectionProxy);
            }
        } catch (TransientObjectException e) {
            //ignore object that are not saved yet
        }
    }

    public org.hibernate.Session getHibernateSession() {
        Object delegate = getEntityManager().getDelegate();
        org.hibernate.Session session = null;
        //This is in SAP J2EE
        if(delegate instanceof org.hibernate.Session){
            session = (org.hibernate.Session) delegate;
        }
        // this is in OpenEJB container
        else if(delegate instanceof HibernateEntityManager){
            HibernateEntityManager hbEm = (HibernateEntityManager) delegate;
            session = hbEm.getSession();
        }
        return session;
    }
}

public static Object getAttributeValue(Object bean, String attributeName){
        Map props = getPropertyDescriptors(bean.getClass(), new String[]{"class"});
        PropertyDescriptor desc = props.get(attributeName);
        if(desc == null) throw new IllegalArgumentException("attribute:" +attributeName + " does not exist in bean "+ bean);
       
        try {
            Object result = desc.getReadMethod().invoke(bean, null);
            return result;
        } catch (IllegalArgumentException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

No comments:

Post a Comment