Java GroupBy/Having 查询的 HQL 问题

Java HQL Issues with GroupBy/Having Query

我必须使用 Hibernate 制作一个 HQL 来找出博物馆警卫人员到他们博物馆的某些频率的总和,一些博物馆警卫人员每小时占用相同的班次 - 我想在这个班次中找到 Mike Jones 频率。

这是我目前拥有的:

select v, m.freq/count(m.id) from Vigilant v inner join v.museums as
m group by m.id having count(m.id) > 0 and v.forename = 'Mike Jones'

这会给我一个 Hibernate 中的对象列表,其中包含一个 Vigilant 和一个数字 - 我得到的数字是正确的,我希望对它们求和 - 即我想 SUM(m.freq/count (m.id)) 和 return 作为休眠的 HQL。

我尝试了多种方法,我设计了一个遵循此路径和子查询的 SQL 解决方案,但 HQL 不允许 FROM 子句中的子查询,这让我回到了这个。现在我不知道怎么回事,因为在 select 语句中添加 SUM 或删除 v 不起作用。

关于如何让它工作的任何帮助?谢谢

You can't group by whole entities:

Neither the group by clause nor the order by clause can contain arithmetic expressions. Hibernate also does not currently expand a grouped entity, so you cannot write group by cat if all properties of cat are non-aggregated. You have to list all non-aggregated properties explicitly.

所以你的查询变成这样:

select 
    v.id,
    v.prop1
    ...,
    v.propn,
    m.freq/count(m.id)
from Vigilant v 
inner join v.museums m
where 
    v.forename = 'Mike Jones'
group by v.id, v.prop1, .., v.propn
  1. prop1...propn 是 Vigilant 的所有属性(EAGER 获取使其进一步复杂化)
  2. having 不是必需的,因为您已经有一个 INNER JOIN,如果没有博物馆,则不会返回 Vigilant
  3. forename 过滤器在 WHERE 子句中更有意义

我的建议是使用更简单的查询:

select 
    v.id,
    m.freq/count(m.id)
from Vigilant v 
inner join v.museums m
where 
    v.forename = 'Mike Jones'
group by v.id

并使用选定的 ID 通过第二个查询检索实体:

select v 
from Vigilant v 
where v.id in (:ids)