Hibernate Criteria分组和聚合

时间:2022-09-16 12:13:18


1.一个聚合错操作,例如cout(*)查询记录数

<span style="font-size:14px;">    Criteria crit = session.createCriteria(User.class);  
crit.setProjection(Projections.rowCount());
int v = (Integer)crit.uniqueResult(); </span>
   注意:setProjection()可以多次使用,但是最后一次会覆盖前面的聚合操作
2.多个聚合操作

 

    ProjectionList proList = Projections.projectionList();  
proList.add(Projections.rowCount());
proList.add(Projections.max("id"));
proList.add(Projections.sum("id"));
crit.setProjection(proList);
List results = crit.list();
Object[] arr = (Object[])results.get(0);
for(Object ob : arr){
System.out.println(ob.toString());
}
  相当与执行:
select count(*),max(id),sum(id) from user 

3.分组 group by

 

Criteria crit = session.createCriteria(User.class);  
crit.setProjection(Projections.rowCount());
crit.setProjection(Projections.groupProperty("name"));
List results = crit.list();
相当于执行:

    select count(*) from user group by name