首页 > 代码库 > Hibernate中的QBC查询

Hibernate中的QBC查询

QBC 查询方式(Query By Criteria)

public void testQBCQuery1(){
		Criteria criteria=session.createCriteria(Student.class);
		List<Student> studentList=criteria.list();
		Iterator it=studentList.iterator();
		while(it.hasNext()){
			Student s=(Student)it.next();
			System.out.println(s);
		}	
	}


带条件查询:
public void testQBCQuery2(){
		Criteria criteria=session.createCriteria(Student.class);
		Criterion c1=Restrictions.like("name", "何%");
		Criterion c2=Restrictions.eq("age", 20);
		criteria.add(c1);
		criteria.add(c2);
		List<Student> studentList=criteria.list();
		Iterator it=studentList.iterator();
		while(it.hasNext()){
			Student s=(Student)it.next();
			System.out.println(s);
		}	
	}


排序:
public void testQBCQuery3(){
		Criteria criteria=session.createCriteria(Student.class);
		criteria.addOrder(Order.desc("age"));
		List<Student> studentList=criteria.list();
		Iterator it=studentList.iterator();
		while(it.hasNext()){
			Student s=(Student)it.next();
			System.out.println(s);
		}	
	}


分页:
public void testQBCQuery4(){
		Criteria criteria=session.createCriteria(Student.class);
		criteria.setFirstResult(2);
		criteria.setMaxResults(2);
		List<Student> studentList=criteria.list();
		Iterator it=studentList.iterator();
		while(it.hasNext()){
			Student s=(Student)it.next();
			System.out.println(s);
		}	
	}

public void testQBCQuery5(){
		Criteria criteria=session.createCriteria(Student.class);
		criteria.setFirstResult(2);
		criteria.setMaxResults(1);
		Student student=(Student)criteria.uniqueResult();
		System.out.println(student);
	}


链式写法:
public void testQBCQuery6(){
		Criteria criteria=session.createCriteria(Student.class);
		List<Student> studentList=criteria
				.setFirstResult(0)
				.setMaxResults(2)
				.list();
		Iterator it=studentList.iterator();
		while(it.hasNext()){
			Student s=(Student)it.next();
			System.out.println(s);
		}	
	}