org.hibernate.LazyInitializationException

This topic contains 22 replies, has 4 voices, and was last updated by  panickert 12 years, 1 month ago.

Viewing 15 posts - 1 through 15 (of 23 total)
  • Author
    Posts
  • #252888 Reply

    schanamolu
    Member

    Hi,

    I’m getting the following exception. Iam using JSF+spring+Hibernate of myeclipse 4.1.1 in my enviornment.

    I got the following exception when It try to get database entity.

    org.hibernate.LazyInitializationException: could not initialize proxy – the owning Session was closed

    Any feed would be appreciated.

    Thanks,
    Sreedhar

    #252894 Reply

    Riyad Kalla
    Member

    What does the code that throws the exception look like? How are you opening/closing the session?

    #252940 Reply

    schanamolu
    Member

    This is service Layer through which DAO’S are accessed.

    ApplicationVO GetApplicationVO (List finalAcmServicesList, String name ){

    List arrayList = new ArrayList();
    Acmservice acmservice = null;

    for (Iterator SvcItr = finalAcmServicesList.iterator(); SvcItr.hasNext(); ){
    acmservice = (Acmservice)SvcItr.next();
    String appName = acmservice.getApplication().getAppname();
    if (appName.compareTo(name)==0)
    arrayList.add(acmservice);
    }

    applicationVO.setApplicationName(name);
    applicationVO.setAppid(acmservice.getApplication().getId().getAppid());
    applicationVO.setCompanyId(acmservice.getApplication().getId().getCompany().getCompanyid());
    applicationVO.setServices(arrayList);

    return applicationVO;
    }

    ***************************************************************************

    The following file is generated by myeclipse —->Add Hibernate Capabilities which manages session management.

    package com.cvg.ap.ws.model.businessobject;

    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.hibernate.cfg.Configuration;

    /**
    * Configures and provides access to Hibernate sessions, tied to the
    * current thread of execution. Follows the Thread Local Session
    * pattern, see {@link http://hibernate.org/42.html}.
    */
    public class HibernateSessionFactory {

    /**
    * Location of hibernate.cfg.xml file.
    * NOTICE: Location should be on the classpath as Hibernate uses
    * #resourceAsStream style lookup for its configuration file. That
    * is place the config file in a Java package – the default location
    * is the default Java package.<br><br>
    * Examples: <br>
    * <code>CONFIG_FILE_LOCATION = “/hibernate.conf.xml”.
    * CONFIG_FILE_LOCATION = “/com/foo/bar/myhiberstuff.conf.xml”.</code>
    */
    private static String CONFIG_FILE_LOCATION = “/hibernate.cfg.xml”;

    /** Holds a single instance of Session */
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

    /** The single instance of hibernate configuration */
    private static final Configuration cfg = new Configuration();

    /** The single instance of hibernate SessionFactory */
    private static org.hibernate.SessionFactory sessionFactory;

    /**
    * Returns the ThreadLocal Session instance. Lazy initialize
    * the <code>SessionFactory</code> if needed.
    *
    * @return Session
    * @throws HibernateException
    */
    public static Session currentSession() throws HibernateException {
    Session session = (Session) threadLocal.get();

    if (session == null || !session.isOpen()) {
    if (sessionFactory == null) {
    try {
    cfg.configure(CONFIG_FILE_LOCATION);
    sessionFactory = cfg.buildSessionFactory();
    } catch (Exception e) {
    System.err
    .println(“%%%% Error Creating SessionFactory %%%%”);
    e.printStackTrace();
    }
    }
    session = (sessionFactory != null) ? sessionFactory.openSession()
    : null;
    threadLocal.set(session);
    }

    return session;
    }

    /**
    * Close the single hibernate session instance.
    *
    * @throws HibernateException
    */
    public static void closeSession() throws HibernateException {
    Session session = (Session) threadLocal.get();
    threadLocal.set(null);

    if (session != null) {
    session.close();
    }
    }

    /**
    * Default constructor.
    */
    private HibernateSessionFactory() {
    }

    }

    ***********************************************************************

    Attached is corresponding applicationContext.xml

    <?xml version=”1.0″ encoding=”UTF-8″?>
    <!DOCTYPE beans PUBLIC “-//SPRING//DTD BEAN//EN” “http://www.springframework.org/dtd/spring-beans.dtd”>

    <beans>

    <bean id=”sessionFactory1″ class=”org.springframework.orm.hibernate3.LocalSessionFactoryBean”>
    <property name=”configLocation”>
    <value>classpath:hibernate.cfg.xml</value>
    </property>
    </bean>

    <bean id=”hibernateTemplate” class=”org.springframework.orm.hibernate3.HibernateTemplate”>
    <property name=”sessionFactory”><ref bean=”sessionFactory1″/></property>
    </bean>

    <bean id=”transactionManager” class=”org.springframework.orm.hibernate3.HibernateTransactionManager”>
    <property name=”sessionFactory”><ref local=”sessionFactory1″/></property>
    </bean>

    <bean id =”userDAO” class=”com.cvg.ap.ws.model.dao.hibernate.UsersDAOImpl”>
    <property name=”hibernateTemplate”><ref bean=”hibernateTemplate”/></property>
    </bean>

    <bean id =”companyDAO” class=”com.cvg.ap.ws.model.dao.hibernate.CompanyDAOImpl”>
    <property name=”hibernateTemplate”><ref bean=”hibernateTemplate”/></property>
    </bean>

    <bean id =”companyAppDAO” class=”com.cvg.ap.ws.model.dao.hibernate.ApplicationDAOImpl”>
    <property name=”hibernateTemplate”><ref bean=”hibernateTemplate”/></property>
    </bean>

    <bean id =”apgroupmembersDAO” class=”com.cvg.ap.ws.model.dao.hibernate.GroupmemberDAOImpl”>
    <property name=”hibernateTemplate”><ref bean=”hibernateTemplate”/></property>
    </bean>

    <bean id =”acmgroupservicesDAO” class=”com.cvg.ap.ws.model.dao.hibernate.AcmgroupserviceDAOImpl”>
    <property name=”hibernateTemplate”><ref bean=”hibernateTemplate”/></property>
    </bean>

    <bean id =”acmservicesDAO” class=”com.cvg.ap.ws.model.dao.hibernate.AcmserviceDAOImpl”>
    <property name=”hibernateTemplate”><ref bean=”hibernateTemplate”/></property>
    </bean>

    <!– User Service Defintion –>
    <bean id=”userTransService” class=”com.cvg.ap.ws.model.service.impl.UserServiceImpl”>

    <property name=”userDAO”><ref local=”userDAO”/></property>
    <property name=”companyDAO”><ref local=”companyDAO”/></property>
    <property name=”companyAppDAO”><ref local=”companyAppDAO”/></property>
    <property name=”apgroupmembersDAO”><ref local=”apgroupmembersDAO”/></property>
    <property name=”acmgroupservicesDAO”><ref local=”acmgroupservicesDAO”/></property>

    <property name=”acmservicesDAO”><ref local=”acmservicesDAO”/></property>

    </bean>

    <bean id=”userService” class=”org.springframework.transaction.interceptor.TransactionProxyFactoryBean”>
    <property name=”transactionManager”><ref local=”transactionManager”/></property>
    <property name=”target”><ref local=”userTransService”/></property>
    <property name=”transactionAttributes”>
    <props>
    <prop key=”get*”>PROPAGATION_REQUIRED,readOnly</prop>
    <prop key=”save*”>PROPAGATION_REQUIRED</prop>
    <prop key=”update*”>PROPAGATION_REQUIRED</prop>
    <prop key=”delete*”>PROPAGATION_REQUIRED</prop>
    </props>
    </property>
    </bean>

    <bean id=”dataSource” class=”org.springframework.jdbc.datasource.SingleConnectionDataSource”>
    <property name=”driverClassName”><value>oracle.jdbc.driver.OracleDriver</value></property>
    <property name=”url”><value>jdbc:oracle:thin:@SPDB1.lab.priceinteractive.com:1521:csndev</value></property>
    <property name=”username”><value>accesspoint3</value></property>
    <property name=”password”><value>accesspoint3</value></property>
    </bean>

    <bean id=”transactionManager1″ class=”org.springframework.jdbc.datasource.DataSourceTransactionManager”>
    <property name=”dataSource”><ref local=”dataSource”/></property>
    </bean>
    </beans>

    Pl let me know..

    Thanks,
    Sreedhar

    #252943 Reply

    Riyad Kalla
    Member

    So which line of code is throwing the exception?

    #252966 Reply

    schanamolu
    Member

    String appName = acmservice.getApplication().getAppname();

    #252989 Reply

    Haris Peco
    Member

    Sreedhar,

    You have two choices

    1) make mapping lazy=”false” – It can be very slow if you map inverse collection

    2) load all data (collections and relations) which you use before closing session
    for your case you close session before call method
    GetApplicationVO
    Try close session after service code

    Best

    #253071 Reply

    schanamolu
    Member

    Hi Riyad,

    1) 1st one make mapping lazy=”false” – It can be very slow if you map inverse collection :— where I need to set lazy=”false” which hbm.xml file should I set this value. We have about 15 hbm.xml files. Should I set in all the files or specific file.

    I didnt get you your second answer Load all data (ons and relations). Can you Please be specific with specific example.

    Thanks,
    Sreedhar

    How

    #253072 Reply

    Haris Peco
    Member

    Sreedhar,

    1) 1st one make mapping lazy=”false” – It can be very slow if you map inverse collection :— where I need to set lazy=”false” which hbm.xml file should I set this value. We have about 15 hbm.xml files. Should I set in all the files or specific file.

    in all *hbm.xml like this
    <hibernate-mapping default-lazy=”false” … >

    if you map all collections (MyEclipse will do this) then this will load almost complete database for every request and it will be slow

    I didnt get you your second answer Load all data (ons and relations). Can you Please be specific with specific example.

    you close session before call GetApplicationVO – GetApplicationVO try load lazy collections and
    hibernate can’t do it out of session

    you can simple call GetApplicationVO before closing session

    If you don’t understand further, please send code which open session and call GetApplicationVO

    Best regards

    #253073 Reply

    schanamolu
    Member

    package com.cvg.ap.ws.model.businessobject;

    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.hibernate.cfg.Configuration;

    /**
    * Configures and provides access to Hibernate sessions, tied to the
    * current thread of execution. Follows the Thread Local Session
    * pattern, see {@link http://hibernate.org/42.html}.
    */
    public class HibernateSessionFactory {

    /**
    * Location of hibernate.cfg.xml file.
    * NOTICE: Location should be on the classpath as Hibernate uses
    * #resourceAsStream style lookup for its configuration file. That
    * is place the config file in a Java package – the default location
    * is the default Java package.<br><br>
    * Examples: <br>
    * <code>CONFIG_FILE_LOCATION = “/hibernate.conf.xml”.
    * CONFIG_FILE_LOCATION = “/com/foo/bar/myhiberstuff.conf.xml”.</code>
    */
    private static String CONFIG_FILE_LOCATION = “/hibernate.cfg.xml”;

    /** Holds a single instance of Session */
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

    /** The single instance of hibernate configuration */
    private static final Configuration cfg = new Configuration();

    /** The single instance of hibernate SessionFactory */
    private static org.hibernate.SessionFactory sessionFactory;

    /**
    * Returns the ThreadLocal Session instance. Lazy initialize
    * the <code>SessionFactory</code> if needed.
    *
    * @return Session
    * @throws HibernateException
    */
    public static Session currentSession() throws HibernateException {
    Session session = (Session) threadLocal.get();

    if (session == null || !session.isOpen()) {
    if (sessionFactory == null) {
    try {
    cfg.configure(CONFIG_FILE_LOCATION);
    sessionFactory = cfg.buildSessionFactory();
    } catch (Exception e) {
    System.err
    .println(“%%%% Error Creating SessionFactory %%%%”);
    e.printStackTrace();
    }
    }
    session = (sessionFactory != null) ? sessionFactory.openSession()
    : null;
    threadLocal.set(session);
    }

    return session;
    }

    /**
    * Close the single hibernate session instance.
    *
    * @throws HibernateException
    */
    public static void closeSession() throws HibernateException {
    Session session = (Session) threadLocal.get();
    threadLocal.set(null);

    if (session != null) {
    session.close();
    }
    }

    /**
    * Default constructor.
    */
    private HibernateSessionFactory() {
    }

    }
    =======================================================================

    ApplicationVO GetApplicationVO (List finalAcmServicesList, String name ){

    List arrayList = new ArrayList();
    Acmservice acmservice = null;

    for (Iterator SvcItr = finalAcmServicesList.iterator(); SvcItr.hasNext(); ){
    acmservice = (Acmservice)SvcItr.next();
    String appName = acmservice.getApplication().getAppname();
    if (appName.compareTo(name)==0)
    arrayList.add(acmservice);
    }

    applicationVO.setApplicationName(name);
    applicationVO.setAppid(acmservice.getApplication().getId().getAppid());
    applicationVO.setCompanyId(acmservice.getApplication().getId().getCompany().getCompanyid());
    applicationVO.setServices(arrayList);

    return applicationVO;
    }

    String appName = acmservice.getApplication().getAppname(); ======This is throwing exception

    org.hibernate.LazyInitializationException: could not initialize proxy – the owning Session was closed

    ============================================================================

    import org.springframework.orm.hibernate3.HibernateCallback;
    import org.springframework.orm.hibernate3.support.*;

    import java.io.*;
    import java.util.*;
    import java.lang.reflect.Type;

    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.hibernate.cfg.Configuration;

    import org.hibernate.*;
    import org.hibernate.criterion.*;

    import com.cvg.ap.ws.model.businessobject.*;

    public abstract class HibernateDaoBase extends HibernateDaoSupport
    {
    protected final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(getClass());

    /**
    * Persist this object to database, first assigning a generated identifier.
    * (Or using the current value of the identifier property
    * if the assigned generator is used.)
    *
    * @return
    */
    public Object save(Object entity)
    {
    Object o = getHibernateTemplate().save(entity);

    if (o == null)
    {
    log.error(“This value should probably not be null. This may mean the object was not created “);
    throw new NullPointerException(“Something may have gone wrong if the returned id is null. Please check”);
    }

    return entity;
    }

    public Object saveNew(Object entity)
    {
    return save(entity);
    }

    /**
    * Refresh a hibernate object
    *
    * @param entity
    * @throws PersistenceException
    */
    public void refresh(final Object entity)
    {
    getHibernateTemplate().execute(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    session.refresh(entity);
    return null;
    }
    });
    }

    /**
    * Save or update this object to database
    *
    * @param entity
    * @throws PersistenceException
    */
    protected void saveOrUpdate(Object entity)
    {
    getHibernateTemplate().saveOrUpdate(entity);
    }

    /**
    * Update this object with the given identifier. If there is a persistent
    * instance with the same identifier, an exception is thrown.
    * <p/>
    * If the given transient instance has a null identifier, an exception will be thrown.
    */
    protected void update(Object entity)
    {
    getHibernateTemplate().update(entity);
    }

    /**
    * Remove this object from the datastore.
    */
    protected void remove(Object entity)
    {
    getHibernateTemplate().delete(entity);
    }

    /**
    * Removes the object from the database with with specified class
    * type and <code>id</code>.
    *
    * @param entityClass
    * @param id
    * @throws PersistenceException
    */
    public void delete(final Class entityClass, final Serializable id)
    {
    getHibernateTemplate().execute(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    Object obj = session.load(entityClass, id);
    session.delete(obj);
    session.flush();
    return null;
    }
    });
    }

    /**
    * Retrieves and <code>Object</code> of the class type specified
    * by <code>c</code>, and having the given <code>id</code>.
    *
    * @param entityClass
    * @param id
    * @return
    * @throws PersistenceException
    */
    protected Object retrieve(Class entityClass, Serializable id)
    {
    return getHibernateTemplate().get(entityClass, id);
    }

    /**
    * Retrieves an <code>Object</code> from the database.
    *
    * @param key the key used to lookup the query in the resource bundle
    * @param value the value that is inserted into the query. May be null
    * if the desired query does not take a parameter.
    * @return Object
    * @throws PersistenceException
    */
    /* protected Object retrieve(String key, Object value, Type type)
    {
    List objects = retrieveObjs(key, value, type);
    if (objects != null)
    {
    if (objects.size() == 0)
    {
    return null;
    }
    else
    {
    return objects.get(0);
    }
    }
    else
    {
    return null;
    }
    }*/

    /**
    * Retrieves an <code>Object</code> from the database.
    *
    * @param key the key used to lookup the query in the resource bundle
    * @param values an array of values to be bound to the “?” placeholders (JDBC IN parameters).
    * @param types an array of Hibernate types of the values
    * @return a distinct list of instances
    * @throws PersistenceException
    * @see Hibernate for access to <tt>Type</tt> instances
    */
    /* protected Object retrieve(String key, Object[] values, Type[] types)
    {
    List objects = retrieveObjs(key, values, types);
    if (objects != null)
    {
    if (objects.size() == 0)
    {
    return null;
    }
    else
    {
    return objects.get(0);
    }
    }
    else
    {
    return null;
    }
    }*/

    /**
    * Retrieves a <code>List</code> of <code>Object</code>s from the database.
    *
    * @param key the key used to lookup the query in the resource bundle
    * @param value the value that is inserted into the query. May be null
    * if the desired query does not take a parameter.
    * @return List will be null if no objects are retrieved
    * @throws PersistenceException
    */
    /* protected List retrieveObjs(final String key, final Object value, final Type type)
    {
    return retrieveObjsByQuery(getQuery(key), value,type);
    }
    */
    /**
    * Retrieves a <code>List</code> of <code>Object</code>s from the database.
    *
    * @param query the key used to lookup the query in the resource bundle
    * @param value the value that is inserted into the query. May be null
    * if the desired query does not take a parameter.
    * @return List will be null if no objects are retrieved
    * @throws PersistenceException
    */
    /* protected List retrieveObjsByQuery(final String query, final Object value, final Type type)
    {
    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    List results = null;
    if (value != null)
    {
    results = session.find(query, value, type);
    }
    else
    {
    results = session.find(query);
    }
    return results;
    }
    });
    }*/

    /**
    * Binding an array of values to “?” parameters in the query string.
    *
    * @param key the key used to lookup the query in the resource bundle
    * @param values an array of values to be bound to the “?” placeholders (JDBC IN parameters).
    * @param types an array of Hibernate types of the values
    * @return a distinct list of instances
    * @throws PersistenceException
    * @see Hibernate for access to <tt>Type</tt> instances
    */
    /* protected List retrieveObjs(final String key, final Object[] values, final Type[] types)
    {
    return retrieveObjsByQuery(getQuery(key), values, types);
    }
    */

    /**
    * Binding an array of values to “?” parameters in the query string.
    *
    * @param query the key used to lookup the query in the resource bundle
    * @param values an array of values to be bound to the “?” placeholders (JDBC IN parameters).
    * @param types an array of Hibernate types of the values
    * @return a distinct list of instances
    * @throws PersistenceException
    * @see Hibernate for access to <tt>Type</tt> instances
    */
    /* protected List retrieveObjsByQuery(final String query, final Object[] values, final Type[] types)
    {
    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    return session.find(query, values, types);
    }
    });
    }*/

    /**
    * Searching based on a query expressed in Hibernate’s query language
    *
    * @param sql
    * @return
    * @throws PersistenceException
    */
    protected List find(final String sql)
    {
    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    return session.getNamedQuery(sql);
    }
    });

    }

    /**
    * Retrieves the HQL query from the resource bundle.
    *
    * @param key the HQL query to lookup
    */
    protected String getQuery(String key)
    {
    return HibernateQueryHelper.getQuery(key);
    }

    /**
    * This method is used to remove duplicate elements in a list.
    *
    * @param list
    * @return
    */
    protected List removeDuplicates(List list)
    {
    if (list == null)
    {
    return null;
    }

    Set uniqueSet = new HashSet();
    uniqueSet.addAll(list);

    List newList = new ArrayList();
    newList.addAll(uniqueSet);
    return newList;

    //return Arrays.asList(uniqueSet.toArray());
    }

    /**
    * Create a query filter for searching
    *
    * @param prefix
    * @param field
    * @param value
    * @return
    */
    protected String createSearchFilter(String prefix, String field, String value)
    {
    String filter = “”;
    if ((value == null) || (value.length() == 0))
    {
    return filter;
    }

    if (value.indexOf(‘*’) != -1)
    {
    value = value.replace(‘*’, ‘%’).toUpperCase();
    filter = ” and upper(” + prefix + “.” + field + “) like ‘” + value + “‘”;
    }
    else
    {
    value = value.toUpperCase();
    filter = ” and upper(” + prefix + “.” + field + “) = ‘” + value + “‘”;
    }
    return filter;
    }

    public List findByCompanyId(final Class cls, final String companyId)
    {

    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    /* Criteria searchCriteria = session.createCriteria(Apcompanyapplications.class);
    searchCriteria.add(Expression.eq(“com.cvg.ap.ws.model.businessobject.Apcompanyapplications.id.apcompany”, company.getCompanyid()));
    return searchCriteria.list();*/

    StringBuffer sb = new StringBuffer(100);
    sb.append(“select c from com.cvg.ap.ws.model.businessobject.Company as c where c.companyid=”);
    sb.append(“‘”);
    sb.append(companyId);
    sb.append(“‘”);
    Query query = session.createQuery(sb.toString());
    List list = query.list();
    return list;

    }
    });
    }

    public List findGroupsByUserId(final Class cls, final Users baseData)
    {
    final Users users = (Users) baseData;

    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    StringBuffer sb = new StringBuffer(100);
    sb.append(“select c from com.cvg.ap.ws.model.businessobject.Groupmember as c where c.id.users=”);
    sb.append(“‘”);
    sb.append(users.getUserid());
    sb.append(“‘”);
    Query query = session.createQuery(sb.toString());
    List list = query.list();
    return list;
    }
    });
    }

    public List findACMGroupServicesByGroupId(final Class cls, final Groups baseData)
    {
    final Groups group = (Groups) baseData;
    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    StringBuffer sb = new StringBuffer(100);
    sb.append(“select c from com.cvg.ap.ws.model.businessobject.Acmgroupservice as c where c.id.groups=”);
    sb.append(“‘”);
    sb.append(group.getGroupid());
    sb.append(“‘”);
    Query query = session.createQuery(sb.toString());
    List list = query.list();
    return list;
    }
    });
    }

    public List findAppNameByApplicationId(final Class cls, final Acmservice baseData)
    {
    final Acmservice acmservices = (Acmservice) baseData;
    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    StringBuffer sb = new StringBuffer(100);
    sb.append(“select c from com.cvg.ap.ws.model.businessobject.Application as c where c.id.company=”);
    sb.append(acmservices.getApplication().getId().getCompany().getCompanyid());
    sb.append(” AND c.id.appname = “);
    sb.append(acmservices.getApplication().getId().getAppid());
    Query query = session.createQuery(sb.toString());
    List list = query.list();
    return list;
    }
    });
    }

    public List findServiceDefinationByServiceId(final Class cls, final Acmservice baseData)
    {
    final Acmservice acmservices = (Acmservice) baseData;
    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    StringBuffer sb = new StringBuffer(100);
    sb.append(“select c from com.cvg.ap.ws.model.businessobject.Acmservicedefinition as c where c.acmservice=”);
    sb.append(acmservices.getAcmserviceid());
    Query query = session.createQuery(sb.toString());
    List list = query.list();
    return list;
    }
    });
    }

    public List findGroupServicesByGroupId(final Class cls, final Groups baseData)
    {
    final Groups group = (Groups) baseData;
    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    StringBuffer sb = new StringBuffer(100);
    sb.append(“select c from com.cvg.ap.ws.model.businessobject.Groupservice as c where c.id.groups=”);
    sb.append(“‘”);
    sb.append(group.getGroupid());
    sb.append(“‘”);
    Query query = session.createQuery(sb.toString());
    List list = query.list();
    return list;
    }
    });
    }

    public List findUserExtServicesByServiceId(final Class cls, final Externalservice baseData)
    {
    final Externalservice service = (Externalservice) baseData;

    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    StringBuffer sb = new StringBuffer(100);
    sb.append(“select c from com.cvg.ap.ws.model.businessobject.Userextservice as c where c.id.externalservice=”);
    sb.append(“‘”);
    sb.append(service.getServiceid());
    sb.append(“‘”);
    Query query = session.createQuery(sb.toString());
    List list = query.list();
    return list;
    }
    });
    }

    public List findUserExtServicesByUserId(final Class cls, final Users baseData)
    {
    final Users users = (Users) baseData;

    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    StringBuffer sb = new StringBuffer(100);
    sb.append(“select c from com.cvg.ap.ws.model.businessobject.Userextservice as c where c.id.users=”);
    sb.append(“‘”);
    sb.append(users.getUserid());
    sb.append(“‘”);
    Query query = session.createQuery(sb.toString());
    List list = query.list();
    return list;
    }
    });
    }

    }

    #253074 Reply

    schanamolu
    Member

    Hi,

    I used my eclipse tool for generating Hibernate Mapping *.hbm.xml files. Please look the sample. Bydefault myeclipse set default-lazy=”false”

    I used HibernateBaseDao Posted Up for data get/update operations.

    I used HibernateSessionFactory.java which was generated myeclipse for session management. Please look the code posted in my previous posting.

    Thanks,
    Sreedhar

    <?xml version=”1.0″?>
    <!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN”
    “http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”>
    <!–
    Mapping file autogenerated by MyEclipse – Hibernate Tools
    –>
    <hibernate-mapping>
    <class name=”com.cvg.ap.ws.model.businessobject.Application” table=”APPLICATION” schema=”ACCESSPOINT3″>
    <composite-id name=”id” class=”com.cvg.ap.ws.model.businessobject.ApplicationId”>
    <key-property name=”appid” type=”java.lang.String”>
    <column name=”APPID” length=”20″ />
    </key-property>
    <key-many-to-one name=”company” class=”com.cvg.ap.ws.model.businessobject.Company”>
    <column name=”COMPANYID” length=”20″ />
    </key-many-to-one>
    </composite-id>
    <property name=”appname” type=”java.lang.String”>
    <column name=”APPNAME” length=”20″ not-null=”true” />
    </property>
    <set name=”acmservices” inverse=”true”>
    <key>
    <column name=”APID” length=”20″ />
    <column name=”COMPANYID” length=”20″ not-null=”true” />
    </key>
    <one-to-many class=”com.cvg.ap.ws.model.businessobject.Acmservice” />
    </set>
    </class>
    </hibernate-mapping>

    #253075 Reply

    Haris Peco
    Member

    Sreedhar,

    I couldn’t found code which make session and call GetApplicationVO.

    I used my eclipse tool for generating Hibernate Mapping *.hbm.xml files. Please look the sample. Bydefault myeclipse set default-lazy=”false”

    MyEclipse doesn’t set default-lazy and it mean that default-lazy=”true” for hibernate >= 3.0

    Best

    #253076 Reply

    schanamolu
    Member

    Hi,

    Below is the samplecode that i was generating.

    acmservice.getApplication().getAppname(); is the line generating exception. getApplication() which in specific (Application table has One to Many relation to AcmService table)

    Let me know..response would be appreciated.

    Thanks,
    Sreedhar
    Let me know

    ApplicationVO GetApplicationVO (List finalAcmServicesList, String name ){

    List arrayList = new ArrayList();
    Acmservice acmservice = null;

    for (Iterator SvcItr = finalAcmServicesList.iterator(); SvcItr.hasNext(); ){
    acmservice = (Acmservice)SvcItr.next();
    String appName = acmservice.getApplication().getAppname();
    if (appName.compareTo(name)==0)
    arrayList.add(acmservice);
    }

    applicationVO.setApplicationName(name);
    applicationVO.setAppid(acmservice.getApplication().getId().getAppid());
    applicationVO.setCompanyId(acmservice.getApplication().getId().getCompany().getCompanyid());
    applicationVO.setServices(arrayList);

    return applicationVO;
    }

    #253080 Reply

    Haris Peco
    Member

    Sreedhar ,

    I saw this code, but your problem is before this – when you call GetApplicationVO then it’s late – you closed session already

    Have you code which create session and call GetApplicationVO ?

    Best
    Peco

    #253082 Reply

    schanamolu
    Member

    Hi Peco,

    Please look HibernateSessionFactory.class which manages session.

    The following file is generated by myeclipse —->Add Hibernate Capabilities which manages session management.

    package com.cvg.ap.ws.model.businessobject;

    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.hibernate.cfg.Configuration;

    /**
    * Configures and provides access to Hibernate sessions, tied to the
    * current thread of execution. Follows the Thread Local Session
    * pattern, see {@link http://hibernate.org/42.html}.
    */
    public class HibernateSessionFactory {

    /**
    * Location of hibernate.cfg.xml file.
    * NOTICE: Location should be on the classpath as Hibernate uses
    * #resourceAsStream style lookup for its configuration file. That
    * is place the config file in a Java package – the default location
    * is the default Java package.<br><br>
    * Examples: <br>
    * <code>CONFIG_FILE_LOCATION = “/hibernate.conf.xml”.
    * CONFIG_FILE_LOCATION = “/com/foo/bar/myhiberstuff.conf.xml”.</code>
    */
    private static String CONFIG_FILE_LOCATION = “/hibernate.cfg.xml”;

    /** Holds a single instance of Session */
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

    /** The single instance of hibernate configuration */
    private static final Configuration cfg = new Configuration();

    /** The single instance of hibernate SessionFactory */
    private static org.hibernate.SessionFactory sessionFactory;

    /**
    * Returns the ThreadLocal Session instance. Lazy initialize
    * the <code>SessionFactory</code> if needed.
    *
    * @return Session
    * @throws HibernateException
    */
    public static Session currentSession() throws HibernateException {
    Session session = (Session) threadLocal.get();

    if (session == null || !session.isOpen()) {
    if (sessionFactory == null) {
    try {
    cfg.configure(CONFIG_FILE_LOCATION);
    sessionFactory = cfg.buildSessionFactory();
    } catch (Exception e) {
    System.err
    .println(“%%%% Error Creating SessionFactory %%%%”);
    e.printStackTrace();
    }
    }
    session = (sessionFactory != null) ? sessionFactory.openSession()
    : null;
    threadLocal.set(session);
    }

    return session;
    }

    /**
    * Close the single hibernate session instance.
    *
    * @throws HibernateException
    */
    public static void closeSession() throws HibernateException {
    Session session = (Session) threadLocal.get();
    threadLocal.set(null);

    if (session != null) {
    session.close();
    }
    }

    ===================================================================================================

    The following code manages session management.

    import org.springframework.orm.hibernate3.HibernateCallback;
    import org.springframework.orm.hibernate3.support.*;

    import java.io.*;
    import java.util.*;
    import java.lang.reflect.Type;

    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.hibernate.cfg.Configuration;

    import org.hibernate.*;
    import org.hibernate.criterion.*;

    import com.cvg.ap.ws.model.businessobject.*;

    public abstract class HibernateDaoBase extends HibernateDaoSupport
    {
    protected final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(getClass());

    /**
    * Persist this object to database, first assigning a generated identifier.
    * (Or using the current value of the identifier property
    * if the assigned generator is used.)
    *
    * @return
    */
    public Object save(Object entity)
    {
    Object o = getHibernateTemplate().save(entity);

    if (o == null)
    {
    log.error(“This value should probably not be null. This may mean the object was not created “);
    throw new NullPointerException(“Something may have gone wrong if the returned id is null. Please check”);
    }

    return entity;
    }

    public Object saveNew(Object entity)
    {
    return save(entity);
    }

    /**
    * Refresh a hibernate object
    *
    * @param entity
    * @throws PersistenceException
    */
    public void refresh(final Object entity)
    {
    getHibernateTemplate().execute(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    session.refresh(entity);
    return null;
    }
    });
    }

    /**
    * Save or update this object to database
    *
    * @param entity
    * @throws PersistenceException
    */
    protected void saveOrUpdate(Object entity)
    {
    getHibernateTemplate().saveOrUpdate(entity);
    }

    /**
    * Update this object with the given identifier. If there is a persistent
    * instance with the same identifier, an exception is thrown.
    * <p/>
    * If the given transient instance has a null identifier, an exception will be thrown.
    */
    protected void update(Object entity)
    {
    getHibernateTemplate().update(entity);
    }

    /**
    * Remove this object from the datastore.
    */
    protected void remove(Object entity)
    {
    getHibernateTemplate().delete(entity);
    }

    /**
    * Removes the object from the database with with specified class
    * type and <code>id</code>.
    *
    * @param entityClass
    * @param id
    * @throws PersistenceException
    */
    public void delete(final Class entityClass, final Serializable id)
    {
    getHibernateTemplate().execute(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    Object obj = session.load(entityClass, id);
    session.delete(obj);
    session.flush();
    return null;
    }
    });
    }

    /**
    * Retrieves and <code>Object</code> of the class type specified
    * by <code>c</code>, and having the given <code>id</code>.
    *
    * @param entityClass
    * @param id
    * @return
    * @throws PersistenceException
    */
    protected Object retrieve(Class entityClass, Serializable id)
    {
    return getHibernateTemplate().get(entityClass, id);
    }

    /**
    * Retrieves an <code>Object</code> from the database.
    *
    * @param key the key used to lookup the query in the resource bundle
    * @param value the value that is inserted into the query. May be null
    * if the desired query does not take a parameter.
    * @return Object
    * @throws PersistenceException
    */
    /* protected Object retrieve(String key, Object value, Type type)
    {
    List objects = retrieveObjs(key, value, type);
    if (objects != null)
    {
    if (objects.size() == 0)
    {
    return null;
    }
    else
    {
    return objects.get(0);
    }
    }
    else
    {
    return null;
    }
    }*/

    /**
    * Retrieves an <code>Object</code> from the database.
    *
    * @param key the key used to lookup the query in the resource bundle
    * @param values an array of values to be bound to the “?” placeholders (JDBC IN parameters).
    * @param types an array of Hibernate types of the values
    * @return a distinct list of instances
    * @throws PersistenceException
    * @see Hibernate for access to <tt>Type</tt> instances
    */
    /* protected Object retrieve(String key, Object[] values, Type[] types)
    {
    List objects = retrieveObjs(key, values, types);
    if (objects != null)
    {
    if (objects.size() == 0)
    {
    return null;
    }
    else
    {
    return objects.get(0);
    }
    }
    else
    {
    return null;
    }
    }*/

    /**
    * Retrieves a <code>List</code> of <code>Object</code>s from the database.
    *
    * @param key the key used to lookup the query in the resource bundle
    * @param value the value that is inserted into the query. May be null
    * if the desired query does not take a parameter.
    * @return List will be null if no objects are retrieved
    * @throws PersistenceException
    */
    /* protected List retrieveObjs(final String key, final Object value, final Type type)
    {
    return retrieveObjsByQuery(getQuery(key), value,type);
    }
    */
    /**
    * Retrieves a <code>List</code> of <code>Object</code>s from the database.
    *
    * @param query the key used to lookup the query in the resource bundle
    * @param value the value that is inserted into the query. May be null
    * if the desired query does not take a parameter.
    * @return List will be null if no objects are retrieved
    * @throws PersistenceException
    */
    /* protected List retrieveObjsByQuery(final String query, final Object value, final Type type)
    {
    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    List results = null;
    if (value != null)
    {
    results = session.find(query, value, type);
    }
    else
    {
    results = session.find(query);
    }
    return results;
    }
    });
    }*/

    /**
    * Binding an array of values to “?” parameters in the query string.
    *
    * @param key the key used to lookup the query in the resource bundle
    * @param values an array of values to be bound to the “?” placeholders (JDBC IN parameters).
    * @param types an array of Hibernate types of the values
    * @return a distinct list of instances
    * @throws PersistenceException
    * @see Hibernate for access to <tt>Type</tt> instances
    */
    /* protected List retrieveObjs(final String key, final Object[] values, final Type[] types)
    {
    return retrieveObjsByQuery(getQuery(key), values, types);
    }
    */

    /**
    * Binding an array of values to “?” parameters in the query string.
    *
    * @param query the key used to lookup the query in the resource bundle
    * @param values an array of values to be bound to the “?” placeholders (JDBC IN parameters).
    * @param types an array of Hibernate types of the values
    * @return a distinct list of instances
    * @throws PersistenceException
    * @see Hibernate for access to <tt>Type</tt> instances
    */
    /* protected List retrieveObjsByQuery(final String query, final Object[] values, final Type[] types)
    {
    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    return session.find(query, values, types);
    }
    });
    }*/

    /**
    * Searching based on a query expressed in Hibernate’s query language
    *
    * @param sql
    * @return
    * @throws PersistenceException
    */
    protected List find(final String sql)
    {
    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    return session.getNamedQuery(sql);
    }
    });

    }

    /**
    * Retrieves the HQL query from the resource bundle.
    *
    * @param key the HQL query to lookup
    */
    protected String getQuery(String key)
    {
    return HibernateQueryHelper.getQuery(key);
    }

    /**
    * This method is used to remove duplicate elements in a list.
    *
    * @param list
    * @return
    */
    protected List removeDuplicates(List list)
    {
    if (list == null)
    {
    return null;
    }

    Set uniqueSet = new HashSet();
    uniqueSet.addAll(list);

    List newList = new ArrayList();
    newList.addAll(uniqueSet);
    return newList;

    //return Arrays.asList(uniqueSet.toArray());
    }

    /**
    * Create a query filter for searching
    *
    * @param prefix
    * @param field
    * @param value
    * @return
    */
    protected String createSearchFilter(String prefix, String field, String value)
    {
    String filter = “”;
    if ((value == null) || (value.length() == 0))
    {
    return filter;
    }

    if (value.indexOf(‘*’) != -1)
    {
    value = value.replace(‘*’, ‘%’).toUpperCase();
    filter = ” and upper(” + prefix + “.” + field + “) like ‘” + value + “‘”;
    }
    else
    {
    value = value.toUpperCase();
    filter = ” and upper(” + prefix + “.” + field + “) = ‘” + value + “‘”;
    }
    return filter;
    }

    public List findByCompanyId(final Class cls, final String companyId)
    {

    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    /* Criteria searchCriteria = session.createCriteria(Apcompanyapplications.class);
    searchCriteria.add(Expression.eq(“com.cvg.ap.ws.model.businessobject.Apcompanyapplications.id.apcompany”, company.getCompanyid()));
    return searchCriteria.list();*/

    StringBuffer sb = new StringBuffer(100);
    sb.append(“select c from com.cvg.ap.ws.model.businessobject.Company as c where c.companyid=”);
    sb.append(“‘”);
    sb.append(companyId);
    sb.append(“‘”);
    Query query = session.createQuery(sb.toString());
    List list = query.list();
    return list;

    }
    });
    }

    public List findGroupsByUserId(final Class cls, final Users baseData)
    {
    final Users users = (Users) baseData;

    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    StringBuffer sb = new StringBuffer(100);
    sb.append(“select c from com.cvg.ap.ws.model.businessobject.Groupmember as c where c.id.users=”);
    sb.append(“‘”);
    sb.append(users.getUserid());
    sb.append(“‘”);
    Query query = session.createQuery(sb.toString());
    List list = query.list();
    return list;
    }
    });
    }

    public List findACMGroupServicesByGroupId(final Class cls, final Groups baseData)
    {
    final Groups group = (Groups) baseData;
    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    StringBuffer sb = new StringBuffer(100);
    sb.append(“select c from com.cvg.ap.ws.model.businessobject.Acmgroupservice as c where c.id.groups=”);
    sb.append(“‘”);
    sb.append(group.getGroupid());
    sb.append(“‘”);
    Query query = session.createQuery(sb.toString());
    List list = query.list();
    return list;
    }
    });
    }

    public List findAppNameByApplicationId(final Class cls, final Acmservice baseData)
    {
    final Acmservice acmservices = (Acmservice) baseData;
    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    StringBuffer sb = new StringBuffer(100);
    sb.append(“select c from com.cvg.ap.ws.model.businessobject.Application as c where c.id.company=”);
    sb.append(acmservices.getApplication().getId().getCompany().getCompanyid());
    sb.append(” AND c.id.appname = “);
    sb.append(acmservices.getApplication().getId().getAppid());
    Query query = session.createQuery(sb.toString());
    List list = query.list();
    return list;
    }
    });
    }

    public List findServiceDefinationByServiceId(final Class cls, final Acmservice baseData)
    {
    final Acmservice acmservices = (Acmservice) baseData;
    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    StringBuffer sb = new StringBuffer(100);
    sb.append(“select c from com.cvg.ap.ws.model.businessobject.Acmservicedefinition as c where c.acmservice=”);
    sb.append(acmservices.getAcmserviceid());
    Query query = session.createQuery(sb.toString());
    List list = query.list();
    return list;
    }
    });
    }

    public List findGroupServicesByGroupId(final Class cls, final Groups baseData)
    {
    final Groups group = (Groups) baseData;
    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    StringBuffer sb = new StringBuffer(100);
    sb.append(“select c from com.cvg.ap.ws.model.businessobject.Groupservice as c where c.id.groups=”);
    sb.append(“‘”);
    sb.append(group.getGroupid());
    sb.append(“‘”);
    Query query = session.createQuery(sb.toString());
    List list = query.list();
    return list;
    }
    });
    }

    public List findUserExtServicesByServiceId(final Class cls, final Externalservice baseData)
    {
    final Externalservice service = (Externalservice) baseData;

    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    StringBuffer sb = new StringBuffer(100);
    sb.append(“select c from com.cvg.ap.ws.model.businessobject.Userextservice as c where c.id.externalservice=”);
    sb.append(“‘”);
    sb.append(service.getServiceid());
    sb.append(“‘”);
    Query query = session.createQuery(sb.toString());
    List list = query.list();
    return list;
    }
    });
    }

    public List findUserExtServicesByUserId(final Class cls, final Users baseData)
    {
    final Users users = (Users) baseData;

    return getHibernateTemplate().executeFind(new HibernateCallback()
    {
    public Object doInHibernate(Session session) throws HibernateException
    {
    StringBuffer sb = new StringBuffer(100);
    sb.append(“select c from com.cvg.ap.ws.model.businessobject.Userextservice as c where c.id.users=”);
    sb.append(“‘”);
    sb.append(users.getUserid());
    sb.append(“‘”);
    Query query = session.createQuery(sb.toString());
    List list = query.list();
    return list;
    }
    });
    }

    }

    #253089 Reply

    Haris Peco
    Member

    Sreedhar,

    Please look HibernateSessionFactory.class which manages session.

    The following file is generated by myeclipse —->Add Hibernate Capabilities which manages session management.

    I know this , but you use this that create/close session when you want

    see your code :

    ApplicationVO GetApplicationVO (List finalAcmServicesList, String name ){
    
    List arrayList = new ArrayList();
    Acmservice acmservice = null;
    
    for (Iterator SvcItr = finalAcmServicesList.iterator(); SvcItr.hasNext(); ){
    acmservice = (Acmservice)SvcItr.next();
    String appName = acmservice.getApplication().getAppname();
    if (appName.compareTo(name)==0)
    arrayList.add(acmservice);
    }
    
    applicationVO.setApplicationName(name);
    applicationVO.setAppid(acmservice.getApplication().getId().getAppid());
    applicationVO.setCompanyId(acmservice.getApplication().getId().getCompany().getCompanyid());
    applicationVO.setServices(arrayList);
    
    return applicationVO;
    }
    

    I suppose next :
    you load collection finalAcmServicesList and close session
    after this you call GetApplicationVO (List finalAcmServicesList, String name )
    and access to
    String appName = acmservice.getApplication().getAppname();
    acmservice have lazy load for Application object and it isn’t loaded – hibernate can’t load
    persistent object after closing session

    you can do it :

    1) set lazy=”false” in Application mappings in services POJO (but you will got exception in other places probably)
    2) set default-lazy=”false” in all mappings (or in services mappings) – this can be slow

    3) left seesion open after load finalAcmServicesList and call GetApplicationVO (List finalAcmServicesList, String name ) in same session

    it’s possible that spring automatic handle session and create/close session when you create
    finalAcmServicesList (before call GetApplicationVO).
    if you use spring you can use transactional session (will not be closed) or do complete
    load finalAcmServicesList and GetApplicationVO in same callback

    you have to send me code which call GetApplicationVO – i can’t help you without this code

    i suppose that code is like this :

    ….
    List finalAcmServicesList = …;
    … // you close session here or spring close session in line before already

    GetApplicationVO(finalAcmServicesList,…);

    Best

Viewing 15 posts - 1 through 15 (of 23 total)
Reply To: org.hibernate.LazyInitializationException