【学习】opensession 与getCurrentsession的区别

来源:互联网 发布:身份证扫描仪 windows 编辑:程序博客网 时间:2024/06/09 14:06

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的openSession方法是每次都去新建一个session 需要自己关闭 这个方法大家应该都了解,3.2以后 getCurrentSession 出了一个优化版的session 他用到了一个session池来进行管理,类似于jdbc的连接池 用完 这个session会自动被回收也就是关闭 但没有实际的关闭 下次在调用直接从池里面去取。这个就比openSession优化了
他还能自己关闭。
但是 这样getCurrentSession 也牺牲了其他方面
只要涉及查询更新操作都要声明事物
声明事物就以为着获取物理连接 其次是耗时
个人认为 延迟加载对他来说应该没意义了
好多人开发人员 都以为getCurrentSession 不用自己写关闭方法 所以好用都用他
在查询的时候也去用 也去声明事物
所以这就是个误区
查询时候咱们可以用openSession  更新操作就去用 getCurrentSession

原创粉丝点击