【发布时间】:2015-05-27 07:17:27
【问题描述】:
我正在使用 Hibernate Criteria,我想为每组值选择最大值,这个最大值必须包含在给定的列表中。
例子:
select t.field1, max(t.field2) as total
from table t
where t.field2 in :givenList
group by t.field1
order by total desc;
我试过这样做:
Criteria criteria = session.createCriteria(Table.class);
DetachedCriteria maxNo = DetachedCriteria.forClass(Table.class);
ProjectionList projection = Projections.projectionList();
projection.add(Projections.groupProperty("id.field1"));
projection.add(Projections.max("id.field2"));
maxNo.setProjection(projection);
criteria.add(Subqueries.propertiesIn(new String[] {"id.field1", "id.field2"}, maxNo));
此代码运行良好,但它只返回每个组的最大值。
如果我尝试添加其他约束,例如:
criteria.add(Property.forName("id.field2").in(givenList));
请求无法正常工作。基本情况,组的最大值是 2,给定的列表是 (0,1),在这种情况下,我们不会收到该组的任何信息。
我希望你能帮助我。提前致谢!
【问题讨论】:
-
请提供示例数据和预期输出,这将帮助您更好地获得正确和快速的答案:)
标签: java hibernate hibernate-criteria detachedcriteria