(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