shh整合出现no session or session was closed

项目使用hibernate3.1 + spring2.0 + struts1.3
set集合延迟加载出现的问题如下
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.jessie.common.model.JyAttribute.codes, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:343)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:86)
at org.hibernate.collection.PersistentSet.iterator(PersistentSet.java:163)

解决:
1.getHibernateTemplate().initialize 准备set集合
return getHibernateTemplate().executeFind(new HibernateCallback(){   
            public Object doInHibernate(Session session)   throws HibernateException, SQLException {   
              Query q = session.createQuery(hql.toString());   
                      List<JyAttribute> attrs = q.list();   
                      for(JyAttribute a : attrs){   
                              getHibernateTemplate().initialize(a.getCodes());   
                      }
                      return attrs;                      
              }});
2.fetch捉取
   //需在映射文件中添加 fetch="join"
return (List)getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query q = session.createQuery(
                        "select distinct p from JyAttribute p left join fetch p.codes" + hql.toString()
                );
                return q.list();
            }
        });  
3.使用OpenSessionInViewFilter管理session,在web.xml中添加
  <filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
注:openSessionViewInFilter未配置成功,还不知何缘由

你可能感兴趣的:(java,Hibernate,orm,配置管理,项目管理)