用hibernate的 getCurrentSession取的 session啥时候关闭?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用hibernate的 getCurrentSession取的 session啥时候关闭?相关的知识,希望对你有一定的参考价值。

getCurrentSession 这个session什么时候关闭?如果用了这个session。save或者updaet操作了 会自动关闭吗?一般项目中除了手动session。close写外 封装好的项目中是什么时候对它进行关闭?? 求大神帮助~

参考技术A 你好,getCurrentSession得到的session是和事务绑定的session,所以:
1,要用getCurrentSession生产的session,就必须有事务环境,意思就是你必须在调用session方法之前,session.beginTransaction();就算你只是get或者query
2,在事务提交之后,即session.getTransaction().commit()之后,session自动关闭,所以你用getCurrentSession,只需要commit事务,不要去调用session.close()
3,你用的是ssh,spring为hibernate的current_session_context_class配置了一个SpringSessionContext来帮你管理getCurrentSession中的session,所以,你在OpenSessionInview的时候,spring就自动的帮你打开了session——>你在执行用AOP包装的事务的时候,事务就开启了——>执行你的业务方法——>提交事务(注意,hibernate管理的getCurrentSession在提交事务的时候才会关闭session,而spring提供的这个SpringSessionContext不会)——>opensessioninview关闭session。
从上面的执行流程可以看出,你在SSH集成的时候,如果用的是getCurrentSession的集成方式,就不能设置hibernate的current_session_context_class为thread,而应该空着,让spring帮你。

Hibernate中getCurrentSession()与openSession()的区别及应用

获取openSession和CurrentSession:

session=HibernateSessionFactory.getSession();
session=HibernateSessionFactory.getSessionFactory().getCurrentSession();

1、getCurrentSession()与openSession()的区别?

* 采用getCurrentSession()创建的session会绑定到当前线程中,而采用openSession()创建的session则不会
* 采用getCurrentSession()创建的session在commit或rollback时会自动关闭,而采用openSession()创建的
    session必须手动关闭

2、使用getCurrentSession()需要在hibernate.cfg.xml文件中加入如下配置

* 如果使用的是本地事务(jdbc事务)
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全局事务(jta事务)
<property name="hibernate.current_session_context_class">jta</property>

以上是关于用hibernate的 getCurrentSession取的 session啥时候关闭?的主要内容,如果未能解决你的问题,请参考以下文章

getCurrentSession() 与 openSession()

hibernate.merge()方法怎么用

hibernate的分页怎么用?

Hibernate怎么用

hibernate怎么用查询

hibernate里‘query’和‘ Criteria’分别啥时候用