zoukankan      html  css  js  c++  java
  • 【Hibernate3.3】 openSession与getCurrentSession区别

    hibernate通过sessionFactory有两种方式获取session:一种是openSession,一种是getCurrentSession

    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 ()。

  • 相关阅读:
    数据表的水平拆分
    高性能网站架构
    文本框内容改变触发事件
    树莓派3B(1)- Raspberry Pi 3B 安装系统并联网
    一年经验Java程序员面经小记
    Windows系统安装总结
    树莓派3B(2)- 配置多个wifi,自动寻找可用网络
    Centos7 Apache实现Http访问SVN资源库
    Centos7搭建svn服务
    读《重构 改善既有代码的设计》有感
  • 原文地址:https://www.cnblogs.com/surge/p/2373107.html
Copyright © 2011-2022 走看看