晚上在测试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()判断!
分享到:
相关推荐
Hibernate Session释放模式
No Hibernate Session bound to thread,没有绑定线程解决办法,找了好久才找到的
Hibernate-nosession浅谈代码案例。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
可以对hibernate的 Session 和 Transaction 有更深入的认识 希望对一些概念比较模糊的人 有帮助
hibernate配置文件,session工厂学习,session链接数据库
Hibernate 中对session的管理!
hibernate中session的管理描述。 hibernate中session的管理描述。
NULL 博文链接:https://former.iteye.com/blog/676665
hibernate session详细方法,值得珍藏
手写hibernate的session实现简单增删改查,适合新手学习hibernate
Hibernate的透明持久化用起来非常舒服,有时甚至忘记了数据库的存在。我身边的朋友经常会分不清save、saveOrUpdate、update的区别,lock、merge、replicate、refresh、evict甚至不知道是干什么用的。而且关于实体...
Hibernate_session_factory_配置
hibernate中session对象的状态详解
NULL 博文链接:https://selvemen.iteye.com/blog/457225
如果传入的参数是持久化对象,Session就计划执行一个delete语句。如果传入的参数是游离对象,先使游离对象被Session关联,使它变为持久化对象,然后计划执行一个delete语句。值得注意的是,Session只有在清理缓存的...
JAVA的hibernate手动获取session的方法
通过xml文件配置数据库连接信息 PO类和数据库表的映射关系通过xml文件配置 模拟Hibernate中Session类的save()、delete()、update()和get()方法
NULL 博文链接:https://stewchicken.iteye.com/blog/938875
hibernate--3.Hibernate数据持久化(通过 Session 操纵对象)
其中Hibernate每次都需要手动创建SessionFactory,Session,手动开启提交关闭事务。而这一切操作完全是由Spring来代替。使持久层更加方便,使开发人员减少持久层操作,把注意力放到业务上。