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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值