简体   繁体   中英

Criteria in Hibernate to return some aggregated results in a List

Here is my code. The problem is my results list always return size of 1 instead of size of 4 as expected. The list should contain values for max,min,avg,count. Thanks for helping

Criteria crit = session.createCriteria(Mastercsv.class);
Mastercsv mastercsv = new Mastercsv();
ProjectionList proList = Projections.projectionList();

proList.add(Projections.max("hostsCount"));
proList.add(Projections.min("hostsCount"));
proList.add(Projections.avg("hostsCount"));
proList.add(Projections.count("installedModule"));
crit.setProjection(proList);
crit.add(Restrictions.eq("installedModule", type));
crit.add(Restrictions.between("dateReported", startDate, endDate));
List results = crit.list();

That is misinterpretation of items in result list. Size of the list is not affected by number of selections (max, min, avg, count). In this case expected size of the list is 1 because it is simple select with aggregate functions and without grouping.

Sole item in list is object array that contains in selections order all four selected values. Result can be explorer with following:

List results = crit.list();
for (Object item: results) {
   Object[] itemArr = (Object[]) item;
   System.out.println("max: "+ itemArr[0].getClass() +" " + itemArr[0]);
   System.out.println("min: "+ itemArr[1].getClass() +" " + itemArr[1]);
   System.out.println("avg: "+ itemArr[2].getClass() +" " + itemArr[2]);
   System.out.println("count: "+ itemArr[3].getClass() +" " + itemArr[3]);
}

Values from array can be assigned then when their type is understood. For example if type of hostsCount is Integer, following can be used:

Integer max = (Integer) itemArr[0];

Because it is known that query does not return multiple rows, instead of Criteria.list we can use:

Object[] itemArr = (Object[]) crit.uniqueResult();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM