Question

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();
Was it helpful?

Solution

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top