Hibernate 查询(或条件):在 Where 子句中使用计数

Hibernate Query (or criteria): using Count in Where Clause

我有 1 class 关注:

public Class Customer{
  @id
  int id;
  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "ParentID")
  Customer parentId
}

我怎样才能 select 所有总 Children 小于 2 的客户?

使用以下类型的查询。这仅供参考。根据您的要求更改代码。

select Customer.customerId , count(Customer.children)
from Customer
group by Customer.customerId
having count(Customer.children)  > 2

我假设您将使用@OneToMany 关系添加孩子。

您可以根据关联客户的数量按父实体过滤进行分组

SELECT p 
FROM Customer c JOIN c.parentId p 
GROUP BY p 
HAVING COUNT(c) > 2

请检查是否有条件是您想要的。

如果 Hibernate 版本完全实现 JPA 规范(在 JPA 2.1 规范中,请参阅第 4.7 节),则应该支持此查询。

我不确定 Hibernate 是否允许这样做。如果您遇到任何麻烦,请考虑 HH - The group by clause 中的内容并注意非聚合属性。