我用了OpenSessionInViewInterceptor报错org.hibernate.HibernateException: collection is not associated with any session,然后又用OpenSessionInViewFilter还是报同样错误,请求终极解决方案,高手帮帮忙!

解决方案 »

  1.   

    spring里的hibernateDaoSupport里采用了回调方式,每个数据库方法都置于一个session中,方法结束了,session也就关闭了,如果采用延迟加载,在方法之外在读collection,就会报异常。建议用spring重新配置事务管理,将session与具体的事务相关联。
      

  2.   

    能把继承这个父类(OpenSessionInViewFilter)的类给我们看?
      

  3.   

    如果那个里面的类没错 那就写个filter类 在到filter类里的dofilter()方法里判断session
      

  4.   

    关于session 我也很想了解..老是报session  was closeed !
    spring重新配置事务管理,将session与具体的事务相关联  怎么配.!
      

  5.   

    LZ,spring在每一次完成之后都会关闭相应的 Session,如果你使用的是延迟加载,那么就需要注意Session关闭的时间,因此,如果一定要使用到延迟加载的话,那么只有在Session关闭之前将 所需要的数据 load进来,即,在同一个事务下或者 在 相同的 session不同的事务下。
    Spring具体事务的开启与关闭是通过spring的事务拦截器来实现的,具体的开启时间和关闭时间,是当 执行到这个方法和退出 这个方法的时候,你可以参考一下spring的官方文档。
      

  6.   

    这个问题确实难搞,设置为fetch="select" lazy="false"倒是可以解决,但是项目数据一多就影响速度!!
      

  7.   


    import org.hibernate.FlushMode;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.springframework.orm.hibernate3.SessionFactoryUtils;public class OpenSessionInViewFilter extends org.springframework.orm.hibernate3.support.OpenSessionInViewFilter {
        
        /**
         * we do a different flushmode than in the codebase
         * here
         */
        protected Session getSession(org.hibernate.SessionFactory sessionFactory) throws org.springframework.dao.DataAccessResourceFailureException {
                Session session = SessionFactoryUtils.getSession(sessionFactory, true);
                session.setFlushMode(FlushMode.COMMIT);
                return session;
        }
        /**
         * we do an explicit flush here just in case
         * we do not have an automated flush
         */
        protected void closeSession(Session session, SessionFactory factory) {
                session.flush();
                super.closeSession(session, factory);
        }
    }用这个类替换你的OpenSessionInView,在web.xml中,如果用到了struts2,记得把OpenSessionInViewFilter的映射放到FilterDispatcher的前面