`
虚弱的java
  • 浏览: 160205 次
  • 性别: Icon_minigender_1
  • 来自: 哈尔滨
社区版块
存档分类
最新评论

Hibernate Session was already closed

阅读更多
晚上在测试hibernate实例时,发生如下的异常信息:
org.hibernate.SessionException: Session was already closed
at org.hibernate.impl.SessionImpl.close(SessionImpl.java:320)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:345)
at $Proxy0.close(Unknown Source)
at com.test.TestHibernate.main(TestHibernate.java:80)

代码结构如下:

Userinfo user = new Userinfo();
   user.setName("tom");
   user.setSex("f");
   user.setAge(28);
Session session = sessionFactory.getCurrentSession();
Transaction transaction =  session.beginTransaction();
transaction.begin();
session.saveOrUpdate(user);
transaction.commit();
session.close();

根据经验判断,异常应该是在session.close()一句抛出来的,Hibernate中SessionImpl类close方法里有这样的代码:
if(colosed()){
   throw new SessionException( "Session was already closed" );  
}

我自己写用session来处理数据的代码中并没有把session关掉,也就是程序并没有执行到关掉session的程序行,那是什么时候session给关掉了呢?根据断点跟踪:
发现transactionContext.managedClose 方法: close()会将已经调用此方法关掉!
所以解决方案就是:
1、当我们使用Session session = sessionFactory.getCurrentSession()时,不去关闭session,而是由其自动关闭
2、如果我们一定要这样儿做,那就用isOpen()判断!




0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics