1. 程式人生 > >Hibernate之Query介面的uniqueResult()方法

Hibernate之Query介面的uniqueResult()方法

如果查詢返回多個值用list()方法

public void testQuery(){
		Configuration config = new Configuration().configure();
		SessionFactory factory = config.buildSessionFactory(); //建立SessionFactory
		Session session = factory.openSession();        //建立Session
		session.beginTransaction();                     //開始事務
		
		Query query = session.createQuery("from Student");
		List list = query.list();  // 用list方法返回多個值
		//List list = session.createQuery("from Student").list();
		for(int i=0;i<list.size();i++){
			Student student = (Student)list.get(i);
			System.out.print(student.getId()+" ");
			System.out.print(student.getName()+" ");
			System.out.print(student.getSex()+" ");
			System.out.print(student.getBirthday());
			System.out.println();
		}		
		
		session.getTransaction().commit();         //提交事務 
		session.close();                           //關閉Session
	}

當確定返回的例項只有一個或者null時 用uniqueResult()方法
public void testGet(){
		Configuration config = new Configuration().configure();
		SessionFactory factory = config.buildSessionFactory();
		Session session = factory.openSession();
		session.beginTransaction();
		
		Query query = session.createQuery("from Student s where s.id=?");
		query.setString(0, "2");
		Student student = (Student)query.uniqueResult();  //當確定返回的例項只有一個或者null時 用uniqueResult()方法
		//Student student = (Student)session.createQuery("from Student s where s.id=?").setString(0,"5").uniqueResult();
		
		System.out.println(student.getName());
		System.out.println(student.getBirthday());
		
	
		session.getTransaction().commit();
		session.close();
	}