通过HQL获取孩子数量

Tho*_*zer 6 java orm hibernate hql

我在父实体和子实体之间有一对多的映射.现在我需要找到与父母列表相关的每个父母的子女数量.我试图用HQL做这个,但我不知道如何在那里得到父母的列表.另外,我不知道如何返回实体本身,而不仅仅是它的ID.我当前的HQL查询是:

select new map(parent.id as parentId, count(*) as childCount) 
from Parent parent left join parent.children children
group by parent.id
Run Code Online (Sandbox Code Playgroud)

但这只返回ID,不会对特定父项进行过滤.

编辑 基于Pascal的答案,我已将查询修改为

select new map(parent as parent, count(elements(parent.children)) as childCount) 
from Parent parent
group by parent
Run Code Online (Sandbox Code Playgroud)

这确实有效,但速度极慢:在同一个数据库上30秒而不是400毫秒.

Pas*_*ent 4

我不是 100% 确定,但是这个呢:

select new map(parent.id, count(elements(parent.children)))
from Parent parent group by parent.id
Run Code Online (Sandbox Code Playgroud)