hibernate 上下文相关的会话(Contextual Session)

来源:互联网 发布:c语言中break的用法 编辑:程序博客网 时间:2024/05/29 15:24

org.hibernate.context.CurrentSessionContext 接口的 Javadoc,那里有关于它的契约的详细讨论。它定义了单一的方法,currentSession(),特定的实现用它来负责跟踪当前的上下文相关的会话。Hibernate 内置了此接口的三种实现:

  • org.hibernate.context.JTASessionContext:当前会话根据 JTA 来跟踪和界定。这和以前的仅支持 JTA 的方法是完全一样的。详情请参阅 Javadoc。

  • org.hibernate.context.ThreadLocalSessionContext:当前会话通过当前执行的线程来跟踪和界定。详情也请参阅 Javadoc。

  • org.hibernate.context.ManagedSessionContext:当前会话通过当前执行的线程来跟踪和界定。但是,你需要负责使用这个类的静态方法将 Session 实例绑定、或者取消绑定,它并不会打开(open)、flush 或者关闭(close)任何 Session




    Hibernate用SessionFactory提供session,并且SessionFactory提供了两种取得session的方法:getCurrentSession()和openSession()。
     
    1.getCurrentSession()和openSession()的区别:
       1>.采用getCurrentSession()创建的session会绑定到当前线程中,即getCurrentSession会取得当前线程中已绑定的session,如果没有,则新建一个session并绑定到线程中。这样,保证了一个线程中各个业务方法使用的都是同一个线程,在编程式事务编程中省去了session的传递,是很方便的。而采用openSession()创建的session则只会新建session,从而不能保证数据的唯一性。
     
       2>.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>