如何使用条件(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();
提前谢谢!
答案 0 :(得分:1)
在hql中可能无法使用from子句中的子查询。 见https://docs.jboss.org/hibernate/stable/core.old/reference/en/html/queryhql-subqueries.html
请注意,HQL子查询可能只出现在select或where中 条款。
我有两个建议可以解决这个问题:订购和限制结果,或者创建一个视图。
将结果限制为您想要的结果:
.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);
在数据库中创建一个视图并从中选择
create view HealthPointSumsByPlayer
as
select sum(point), player_id
from Health_Points
group by player_id;
然后从那里选择(通过hql)。