`
mamaoyuan625
  • 浏览: 173375 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Hibernate中拿到session的两种方式

阅读更多
1:openSession()
Configuration cf = new Configuration().configure();
SessionFactory sf = cf.buildSessionFactory();
Session session = sf.openSession();

2:getCurrentSession():

Configuration cf = new Configuration().configure(); 
cf.buildSessionFactory().getCurrentSession();

 区别:

* 采用getCurrentSession()创建的session会绑定到当前线程中,而用openSession()
   创建的session则不会
 * 采用getCurrentSession()创建的session在commit或rollback时会自动关闭,而采用openSession()
   创建的session必须要显示的手动关闭session.close();

 

使用getCurrentSession()需要在hibernate.cfg.xml文件中加入如下配置:
 * 如果使用的是本地事务(jdbc事务)
 <property name="hibernate.current_session_context_class">thread</property>
 * 如果使用的是全局事务(jta事务)
 <property name="hibernate.current_session_context_class">jta</property>    

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics