gpt4 book ai didi

java - Hibernate 标准 MAX 或 SUM

转载 作者:行者123 更新时间:2023-12-02 12:18:08 25 4
gpt4 key购买 nike

如何使用标准(JAVA)实现此 HQL

"SELECT MAX(pointsum) FROM (SELECT SUM(h.point) as pointsum FROM HealthPoint h WHERE h.player.partner = :partner GROUP BY h.player)"

我已经对此进行了测试,但我得到了它,但我找不到属性pointsum

DetachedCriteria detachedPlayer = DetachedCriteria.forClass(Player.class);
detachedPlayer.add(Restrictions.eq("partner", partner));
detachedPlayer.setProjection(Projections.property("id"));

Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(HealthPoint.class);
criteria.add(Subqueries.propertyIn("player", detachedPlayer));
ProjectionList proj = Projections.projectionList();
proj.add(Projections.sum("point"));
proj.add(Projections.groupProperty("player"));
criteria.setProjection(Projections.alias(proj, "pointsum"));
criteria.setProjection(Projections.max("pointsum"));
return (Integer) criteria.uniqueResult();

提前谢谢您!

最佳答案

hql 不支持

from 子句中的子查询在 hql 中可能不可用。请参阅https://docs.jboss.org/hibernate/stable/core.old/reference/en/html/queryhql-subqueries.html

Note that HQL subqueries may occur only in the select or whereclauses.

<小时/>

其他选项

我有两个建议来解决这个问题:排序并限制结果,或者创建一个 View 。

  1. 将结果限制为您想要的结果:

    .createQuery("SELECT SUM(h.point) as pointsum FROM HealthPoint h WHERE h.player.partner = :partner GROUP BY h.player order by pointsum desc")
    .limit(1);
  2. 在数据库中创建一个 View 并从中进行选择

    create view HealthPointSumsByPlayer 
    as
    select sum(point), player_id
    from Health_Points
    group by player_id;

然后从中选择(通过 hql)。

关于java - Hibernate 标准 MAX 或 SUM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46002348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com