Hibernate openSession() 和 getCurrentSession的区别
来源:互联网 发布:matplotlib python 编辑:程序博客网 时间:2024/04/30 06:24
Hibernate openSession() 和 getCurrentSession的区别
getHiberanteTemplate 、getCurrentSession和OpenSession
采用getCurrentSession()创建的Session会绑定到当前的线程中去、而采用OpenSession()则不会。
采用getCurrentSession()创建的Session在commit或rollback后会自动关闭,采用OpenSession()必须手动关闭。
采用getCurrentSession()需要在Hibernate.cfg.xml配置文件中加入如下配置:
如果是本地事务,及JDBC一个数据库:
<propety name=”Hibernate.current_session_context_class”>thread</propety>
如果是全局事务,及jta事务、多个数据库资源或事务:
<propety name=”Hibernate.current_session_context_class”>jta</propety>
使用spring的getHiberanteTemplate 就不需要考虑事务管理和session关闭的问题:
openSession创建session时autoCloseSessionEnabled参数为false,即在事务结束后不会自动关闭session,需要手动关闭,如果不关闭将导致session关联的数据库连接无法释放,最后资源耗尽而使程序当掉。
getCurrentSession创建session时autoCloseSessionEnabled,flushBeforeCompletionEnabled都为true,并且session会同sessionFactory组成一个map以sessionFactory为主键绑定到当前线程。
getCurrentSession():从上下文(配置文件current_session_context_class: thread 使用Connection自动管理;jta(java transaction api) 由Application Server提供的分布式事务管理,Tomcat本身不具备此能力,JBoss、WebLogic具备)找,如果有,则用旧的,否则创建新的,事务提交自动Close;
getCurrentSession本地事务(本地事务:jdbc)时 要在配置文件里进行如下设置:
如果使用的是本地事务(jdbc事务)
<property name="hibernate.current_session_context_class">thread</property>
如果使用的是全局事务(jta事务)
<property name="hibernate.current_session_context_class">jta</property>
总之:
getCurrentSession () 使用当前的session
openSession() 重新建立一个新的session
在一个应用程序中,如果DAO 层使用Spring 的hibernate 模板,通过Spring 来控制session 的生命周期,则首选getCurrentSession ()。
- hibernate 的openSession和getCurrentSession的区别
- Hibernate openSession() 和 getCurrentSession的区别
- Hibernate openSession() 和 getCurrentSession的区别
- Hibernate中openSession 和 getCurrentSession 的区别
- Hibernate 中 openSession()和getCurrentSession() 的区别
- Hibernate openSession()和getCurrentSession()的区别
- Hibernate openSession() 和 getCurrentSession的区别
- hibernate之openSession()和getCurrentSession()的区别
- Hibernate openSession() 和 getCurrentSession的区别
- hibernate: openSession() 和getCurrentSession()的区别
- Hibernate openSession() 和 getCurrentSession的区别 .
- Hibernate的openSession和getCurrentSession区别
- hibernate中 openSession和getCurrentSession的区别
- Hibernate openSession() 和 getCurrentSession的区别
- 【Hibernate】OpenSession和getCurrentSession的区别
- Hibernate openSession() 和 getCurrentSession的区别
- Hibernate getCurrentSession()和openSession()的区别
- Hibernate openSession() 和 getCurrentSession的区别
- 数据结构与算法(C语言版)__选择排序
- AngularJS指令中的compile与link函数解析
- 【腾讯TMQ】30分钟轻松搞定代码瘦身
- 阿里云centos7创建ipv6隧道
- 关于内部类的一些Demo要点
- Hibernate openSession() 和 getCurrentSession的区别
- 浅谈软件兼容性测试
- ConvertUtils工具类的使用
- 微信小程序(微信应用号)组件讲解[申明:来源于网络]
- android5.x之Activity过渡动画
- ElasticSearch详解一之——client连接
- build spark standalone NoClassDefFoundError com/fasterxml/jackson/databind/Module
- [Swift]String Relative
- AdvStringGrid 使用技巧(2)(转载)