简体   繁体   English

Hibernate中的条件以在列表中返回一些汇总结果

[英]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. 问题是我的结果列表总是返回大小1而不是预期的4。 The list should contain values for max,min,avg,count. 该列表应包含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. 在这种情况下,列表的预期大小为1,因为它是带有聚合函数且没有分组的简单选择。

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: 例如,如果hostsCount类型为Integer,则可以使用以下内容:

Integer max = (Integer) itemArr[0];

Because it is known that query does not return multiple rows, instead of Criteria.list we can use: 因为众所周知查询不会返回多行,所以我们可以使用Criteria.list代替:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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