Session is closed ;nested exception is org.hibernate.SessionException: Session is closed解决方案

 

关于Session is closed 的问题,目前碰到三种情况,同时有三种解决方案;

 

 

、通过getSession()方法获得session进行操作造成的session关闭。

 

这种方式获得的session在方法执行结束之后不会自动关闭连接,也就是说我们必须通过session.close()或者releaseSession(session)来手动进行关闭,否则会造成内存泄露或者连接耗尽等问题。

 

如果对进行事务控制,那么spring框架会自动为我们关闭session,此种情况(session.close())下,会抛出异常:

  1.  org.springframework.orm.hibernate3.HibernateSystemException: Session is closed; nested exception is org.hibernate.SessionException: Session is closed   
  2. …   
  3. org.hibernate.SessionException: Session is closed  

解决方案:提示session已经关闭。在代码中通过releaseSession(session)的方法来关闭session,则不会抛出异常

 

参考:http://blog.csdn.net/xiangsuixinsheng/article/details/6451752

 

二、getHibernateTemplate 和 getSession 操作造成的session关闭

在进行两张以上的表操作的时候,同时调用了 getHibernateTemplate 和 getSession 操作数据 ,就出现了异常:

org.springframework.orm.hibernate3.HibernateSystemException: Session is closed; nested exception is org.hibernate.SessionException: Session is closed

org.hibernate.SessionException: Session is closed

 

因为在 getSession 里面是手动设置关闭的 session,getHibernateTemplate的session是系统把我们关闭的,所以当你事务里面调用了两张模式,就会造成session关闭。

解决方案:全部统一使用getHibernateTemplate操作数据,这样session就由系统关闭。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章