SessionFactroy的openSession()和getCurrentSession()的区别

openSession()  每次都是新的 , 每次都需要 close()
getCurrentSession()  从运行环境的上下文 ( 当前线程 ) 中找 , 如果有 , 就取得 . 如果没有 , 创建新的 . 事务提交之前不会 close(), 提交后会自动 close()------------- 用途:界定事务边界
有点抽象.....
 
看图作文....
假定客户端访问UserManager,添加一个用户.在添加的同时,还要做一个日志记录.就要用到事务,把添加用户和添加日志的操作放在一个事务中,这时如果用openSession()的话,那么两个操作相当于开了两个新的session,它们就不属于一个事务了;用getCurrentSession()的话,只要是在commit之前,取得的session都会是同一个.所以必须用getCurrentSession().
 
如果要使用getCurrentSession()必须设置current_session_context_class
          current_session_context_class常用取值thread或jta---java transaction api分布式事务管理(tomcat不具备jta能力)
 
 
1、getCurrentSession()与openSession()的区别 
* 采用getCurrentSession()创建的session会绑定到当前线程中,而采用openSession() 
创建的session则不会 
* 采用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> 

在SessionFactory启动的时候,Hibernate会根据配置创建相应的CurrentSessionContext,在 getCurrentSession()被调用的时候,实际被执行的方法是CurrentSessionContext.currentSession()。在currentSession()执行时,如果当前Session 为空,currentSession 会调用SessionFactory 的openSession。所以getCurrentSession() 对于Java EE 来说是更好的获取Session 的方法。 

sessionFactory.getCurrentSession()可以完成一系列的工作,当调用时,hibernate将session绑定到当前线程,事务结束后,hibernate将session从当前线程中释放,并且关闭session,当再次调用getCurrentSession()时,将得到一个新的session,并重新开始这一系列工作。 
这样调用方法如下: 


Java代码     收藏代码
  1. Session session = HibernateUtil.getSessionFactory().getCurrentSession();  
  2. session.beginTransaction();  
  3. Event theEvent = new Event();  
  4. theEvent.setTitle(title);  
  5. theEvent.setDate(theDate);  
  6. session.save(theEvent);  
  7. session.getTransaction().commit();  



不需要close session了 

你可能感兴趣的:(opensession(),SessionFactroy)