openSession 与 getCurrentSession的区别 openSession 与 getCurrentSession的区别

openSession 与 getCurrentSession的区别

 

一、openSession 每一次得到的是一个全新的session对象,而getCurrentSession得到的是与当前线程绑定的session对象html

 

[java]  view plain copy print ?
  1. package cn.kiwifly.view;  
  2.   
  3. import org.hibernate.SessionFactory;  
  4. import org.hibernate.cfg.Configuration;  
  5. import org.hibernate.classic.Session;  
  6.   
  7. import cn.kiwifly.util.MySessionFactory;  
  8.   
  9. public class View {  
  10.   
  11.     public static void main(String[] args) {  
  12.   
  13.         Configuration configuration = new Configuration().configure();  
  14.         SessionFactory sf = configuration.buildSessionFactory();  
  15.           
  16.         Session sessionOpen1 = sf.openSession();  
  17.         Session sessionOpen2 = sf.openSession();  
  18.           
  19.         Session sessionThread1 = sf.getCurrentSession();  
  20.         Session sessionThread2 = sf.getCurrentSession();  
  21.           
  22.         System.out.println(sessionOpen1.hashCode() + "<-------->" + sessionOpen2.hashCode());  
  23.         System.out.println(sessionThread1.hashCode() + "<-------->" + sessionThread2.hashCode());  
  24.           
  25.   
  26.     }  
  27.   
  28. }  

上面代码输出结果:java

546579839<-------->1579795854
141106670<-------->141106670浏览器

 

二、openSession不须要配置,而getCurrentSession须要配置安全

1中代码若是直接运行会报错,要在hibernate.cfg.xml中加入以下代码才行session

 

[html]  view plain copy print ?
  1. <property name="current_session_context_class">thread</property>  

 

这里咱们是让session与当前线程绑定,这里的线程范围应该是一次浏览器的会话过程,也就是说打开网站和关闭浏览器这个时间段。post

 

三、openSession须要手动关闭,而getCurrentSession系统自动关闭网站

openSession出来的session要经过:ui

 

[java]  view plain copy print ?
  1. session.close();  
而getSessionCurrent出来的session系统自动关闭,若是本身关闭会报错

 

 

四、Session是线程不一样步的,要保证线程安全就要使用getCurrentSessionurl

相关文章
相关标签/搜索