(hibernate之一)Sessionfactory的getCurrentSession与openSession的区别

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();
public void test() {       
//openSession()始终创建新的session       
Session session1=sessionFactory.openSession();        
Session session3=sessionFactory.openSession();        
//输出为false       
System.out.println(session1==session3);        
//getCurrentSession() 必须配置 <property name="current_session_context_class">thread</property>        //因为getCurrentSession()要根据上下文来生成session,如果上下文存在session则不创建新的session,否则创建新的       
Session session2=sessionFactory.getCurrentSession();               
Session session4=sessionFactory.getCurrentSession();               
//输出为true       
System.out.println(session2==session4);               
//getCurrentSession()生成的session提交事务时会自动close,并且session不能再被用       
Session session5=sessionFactory.getCurrentSession();          
session5.beginTransaction();        
session5.getTransaction().commit();                       
Session session6=sessionFactory.getCurrentSession();               
//输出为false       
System.out.println(session5==session6);           
 }

结论:
在一个应用程序中,如果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,并且开始一个新的工作单元。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值