- 借助hibernate提供的接口的一种查询方式
- 比hql更面向对象的查询方式
普通查询
public void testQBCQuery1(){ Criteria sriteria=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=Restriction.like("name","张%"); //添加限制条件;关键字用属性名 Criterion c2=Restrictions.eq("age",10); 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)itt.next(); System.out.println(s); } }
分页查询
public void testQBCQuery4(){ Criteria criteria=session.createCriteria(Student.class); criteria.setFirstResult(0); //从第一条开始查询 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.setMaxRresult(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(2) .setMaxResults(2) .list(); Iterator it=studentList.iterator(); while(it.hasNext()){ Student s=(Student)it.next(); System.out.println(s); } }