简体   繁体   English

休眠查询(或条件):在Where子句中使用Count

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

I have 1 class following: 我有以下1个课程:

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

How can I select all Customer which have total Children less more than 2? 我如何可以选择共有儿童小于2以上所有的客户?

Use following type of query. 使用以下类型的查询。 This is only for reference. 仅供参考。 Make changes in code according to your requirement. 根据您的要求更改代码。

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

I am assuming you'll add childrens using @OneToMany relationship. 我假设您将使用@OneToMany关系添加子项。

You can group by the parent entity filtering according the amount of associated customers 您可以按父实体分组,根据关联客户的数量进行过滤

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

Please check if having condition is what you want. 请检查是否有您想要的条件。

This query should be supported if the Hibernate version fully implements the JPA Specification (in JPA 2.1 specs see section 4.7). 如果Hibernate版本完全实现了JPA规范(在JPA 2.1规范中,请参见4.7节),则应支持该查询。

I am not sure if Hibernate allows to do that. 我不确定Hibernate是否允许这样做。 If you suffer any trouble, consider what says in HH - The group by clause and be aware about non-aggregated properties. 如果遇到任何麻烦,请考虑HH-group by子句中的内容,并注意未聚合的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM