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

 

posted on 2012-01-18 01:21  穆穆  阅读(4106)  评论(0编辑  收藏  举报