Hibernate条件MAX的SUM

时间:2017-09-01 14:22:04

标签: java hibernate hql criteria

如何使用条件(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();

提前谢谢!

1 个答案:

答案 0 :(得分:1)

不支持hql

在hql中可能无法使用from子句中的子查询。 见https://docs.jboss.org/hibernate/stable/core.old/reference/en/html/queryhql-subqueries.html

  

请注意,HQL子查询可能只出现在select或where中   条款。

其他选项

我有两个建议可以解决这个问题:订购和限制结果,或者创建一个视图。

  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. 在数据库中创建一个视图并从中选择

    create view HealthPointSumsByPlayer 
    as 
      select sum(point), player_id 
      from Health_Points 
      group by player_id;
    
  3. 然后从那里选择(通过hql)。