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


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);
	   
	}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM