zoukankan      html  css  js  c++  java
  • openSession 与 getCurrentSession的区别

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

    package cn.kiwifly.view;
    
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.classic.Session;
    
    import cn.kiwifly.util.MySessionFactory;
    
    public class View {
    
    	public static void main(String[] args) {
    
    		Configuration configuration = new Configuration().configure();
    		SessionFactory sf = configuration.buildSessionFactory();
    		
    		Session sessionOpen1 = sf.openSession();
    		Session sessionOpen2 = sf.openSession();
    		
    		Session sessionThread1 = sf.getCurrentSession();
    		Session sessionThread2 = sf.getCurrentSession();
    		
    		System.out.println(sessionOpen1.hashCode() + "<-------->" + sessionOpen2.hashCode());
    		System.out.println(sessionThread1.hashCode() + "<-------->" + sessionThread2.hashCode());
    		
    
    	}
    
    }
    

    上面代码输出结果:

    546579839<-------->1579795854
    141106670<-------->141106670


    2、openSession不需要配置,而getCurrentSession需要配置

    1中代码如果直接运行会报错,要在hibernate.cfg.xml中加入如下代码才行

    	<property name="current_session_context_class">thread</property>

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


    3、openSession需要手动关闭,而getCurrentSession系统自动关闭

    openSession出来的session要通过:

    session.close();
    而getSessionCurrent出来的session系统自动关闭,如果自己关闭会报错


    4、Session是线程不同步的,要保证线程安全就要使用getCurrentSession




  • 相关阅读:
    redis发布订阅
    redis学习笔记(面试题)
    redis安全 (error) NOAUTH Authentication required
    HDU3001 Travelling —— 状压DP(三进制)
    POJ3616 Milking Time —— DP
    POJ3186 Treats for the Cows —— DP
    HDU1074 Doing Homework —— 状压DP
    POJ1661 Help Jimmy —— DP
    HDU1260 Tickets —— DP
    HDU1176 免费馅饼 —— DP
  • 原文地址:https://www.cnblogs.com/kiwifly/p/4435869.html
Copyright © 2011-2022 走看看