码迷,mamicode.com
首页 > 其他好文 > 详细

getCurrentSession 与 openSession区别

时间:2017-12-31 14:43:03      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:有关   代码   hiberna   调用   ssi   nat   get   commit   session   

getCurrentSession () 使用当前的session
openSession()重新建立一个新的session

 

使用SessionFactory.getCurrentSession()需要在hibernate.cfg.xml中如下配置:

* 如果采用jdbc独立引用程序配置如下:
<property name="hibernate.current_session_context_class">thread</property>
* 如果采用了JTA事务配置如下 
<property name="hibernate.current_session_context_class">jta</property>
Session session = HibernateUnit.getSessionFactory().getCurrentSession();
session.beginTransaction();
....
session.getTransaction().commit();

 

使用openSession()不需要配置如上的hibernate.cfg.xml配置

代码如下:

        Session session=HibernateUtils.openSession();
        Transaction transaction = session.beginTransaction();
        .......
        transaction.commit();
        session.close();

j

结论:在一个应用程序中,如果DAO 层使用Spring 的hibernate 模板,通过Spring 来控制session 的生命周期,则首选getCurrentSession ()

      如果使用的是getCurrentSession来创建session的话,在commit后,session就自动被关闭了,不用再session.close()了。

    但是如果使用的是openSession方法创建的session的话,那么必须显示的关闭session,也就是调用session.close()方法。这样commit后,session并没有关闭

    getcurrentSession()的Session 在第一次被使用的时候,即第一次调用getCurrentSession()的时候,其生命周期就开始。

    然后她被Hibernate绑定到当前线程。当事物结束的时候,不管是提交还是回滚,Hibernate会自动把Session从当前线程剥离,并且关闭。

    若在次调用 getCurrentSession(),会得到一个新的Session,并且开始一个新的工作单元。

 

getCurrentSession 与 openSession区别

标签:有关   代码   hiberna   调用   ssi   nat   get   commit   session   

原文地址:https://www.cnblogs.com/weishao-lsv/p/8157618.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!