zoukankan      html  css  js  c++  java
  • Hibernate中的GetCurrentSession()方法

    从3.0.1版本开 始,Hibernate增加了SessionFactory.getCurrentSession()方法。

    采用getCurrentSession()创建的session在commit或rollback时会自动关闭,如果commit()之后再关闭,就会报session已经关闭的错误;但是如果不commit()而执行关闭,虽然不会报什么错误,但是这时观察数据库添加数据是没有成功的,而openSession必须手动关闭。

    在一个应用程序中,如果DAO 层使用Spring来控制session 的生命周期,则首选getCurrentSession()。

    在 SessionFactory 启动的时候,Hibernate 会根据配置创建相应的 CurrentSessionContext,在 getCurrentSession()被调用的时候,实际被执行的方法是 CurrentSessionContext.currentSession()。在 currentSession() 执行时,如果当前Session 为空,currentSession 会调用 SessionFactory的openSession。

    getCurrentSession配置:

    如果使用的是本地事务(jdbc事务)

    <property name="hibernate.current_session_context_class">thread</property>

    如果使用的是全局事务(jta事务)

    <property name="hibernate.current_session_context_class">jta</property>
  • 相关阅读:
    python_07
    python_01
    python_06
    JDBC批处理
    JDBC处理大数据
    利用PreparedStatement预防SQL注入
    利用工厂模式实现serviec层和dao层解耦
    jdbc入门
    EL表达式详解
    购物车案列
  • 原文地址:https://www.cnblogs.com/wdnnccey/p/5982540.html
Copyright © 2011-2022 走看看