简体   繁体   中英

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

I have 1 class following:

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?

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.

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).

I am not sure if Hibernate allows to do that. If you suffer any trouble, consider what says in HH - The group by clause and be aware about non-aggregated properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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