【问题标题】:Hibernate Criteria - Max value from a given listHibernate Criteria - 给定列表的最大值
【发布时间】: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


【解决方案1】:

我找到了解决方案。

maxNo.add(Restrictions.in("id.field2", givenList));

实际上,我将限制放在标准中是错误的。我们应该将 Restrictions 放在 DetachedCriteria 中。

还是谢谢你

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 2011-08-25
    • 2021-03-27
    • 1970-01-01
    • 2017-02-16
    • 1970-01-01
    • 2011-04-23
    相关资源
    最近更新 更多