Hibernate openSession() 和 getCurrentSession的区别java
getHiberanteTemplate 、getCurrentSession和OpenSession
采用getCurrentSession()建立的Session会绑定到当前的线程中去、而采用OpenSession()则不会。spring
采用getCurrentSession()建立的Session在commit或rollback后会自动关闭,采用OpenSession()必须手动关闭。数据库
采用getCurrentSession()须要在Hibernate.cfg.xml配置文件中加入以下配置:api
若是是本地事物,及JDBC一个数据库:session
<propety name=”Hibernate.current_session_context_class”>thread</propety>分布式
若是是全局事物,及jta事物、多个数据库资源或事物资源:hibernate
<propety name=”Hibernate.current_session_context_class”>jta</propety>线程
使用spring的getHiberanteTemplate 就不须要考虑事务管理和session关闭的问题:xml
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 ()。