一、基本查询
1 Session session = HibernateUtils.getSession();2 //创建QBC查询接口的实现类3 Criteria criteria = session.createCriteria(Person.class);4 //查询对象列表5 ListpersonList = criteria.list();
单个属性的查询
1 //创建查询接口的实现类2 Criteria criteria = session.createCriteria(Person.class);3 //获得具体查询的属性4 PropertyProjection pp = Projections.property("pname");5 //设置具体查询的列6 criteria.setProjection(pp);7 ListnameList = criteria.list();
多个属性的查询
1 //创建查询接口的实现类 2 Criteria criteria = session.createCriteria(Person.class); 3 //获得具体查询的属性 4 PropertyProjection pp = Projections.property("pname"); 5 PropertyProjection pp1 = Projections.property("pgender"); 6 //创建要查询列的集合 7 ProjectionList pList = Projections.projectionList(); 8 pList.add(pp); 9 pList.add(pp1);10 //设置具体查询的列11 criteria.setProjection(pList);12 List
二、统计查询
1 //创建查询接口的实现类 2 Criteria criteria = session.createCriteria(Person.class); 3 //设置要查询统计的属性 4 AggregateProjection ap = Projections.max("salary"); 5 criteria.setProjection(ap); 6 Object result = criteria.uniqueResult(); 7 System.out.println(result); 8 //查询总数 9 criteria.setProjection(Projections.rowCount());10 Object result2 = criteria.uniqueResult();11 System.out.println(result2);12 //查询平均值13 criteria.setProjection(Projections.avg("salary"));14 Object result3 = criteria.uniqueResult();15 System.out.println(result3);
三、分组统计查询
1 //创建查询接口的实现类 2 Criteria criteria = session.createCriteria(Person.class); 3 //创建查询项的集合 4 ProjectionList pl = Projections.projectionList(); 5 //设置要查询的属性 6 PropertyProjection pp1 = Projections.property("pgender"); 7 AggregateProjection ap = Projections.max("salary"); 8 PropertyProjection pp = Projections.groupProperty("pgender"); 9 pl.add(pp1);10 pl.add(ap);11 pl.add(pp);12 criteria.setProjection(pl);13 List
四、排序
1 Criteria criteria = session.createCriteria(Person.class);2 criteria.addOrder(Order.desc("salary"));3 ListpList = criteria.list();
五、分页查询
1 Criteria criteria = session.createCriteria(Person.class);2 //设置分页条件3 criteria.setFirstResult(0);4 criteria.setMaxResults(3);5 Listlist = criteria.list();
六、限定查询
1 //创建查询接口的实现类2 Criteria criteria = session.createCriteria(Person.class);3 //创建查询条件4 Criterion c = Restrictions.eq("id", 4);5 criteria.add(c);6 Listlist = criteria.list();
1 //创建查询接口的实现类2 Criteria criteria = session.createCriteria(Person.class);3 //创建查询条件,默认AND链接4 Criterion c = Restrictions.ge("salary", 300);5 Criterion c1 = Restrictions.le("salary", 500);6 criteria.add(c);7 criteria.add(c1);8 Listlist = criteria.list();
1 //创建查询接口的实现类2 Criteria criteria = session.createCriteria(Person.class);3 //创建查询条件4 Criterion c = Restrictions.and(Restrictions.ge("salary", 400),Restrictions.eq("pgender", 0));5 criteria.add(c);6 Listlist = criteria.list();
七、模糊查询
1 //创建查询接口的实现类2 Criteria criteria = session.createCriteria(Person.class);3 //创建查询条件4 Criterion c = Restrictions.like("pname", "张%");5 criteria.add(c);6 Listlist = criteria.list();