简体   繁体   中英

Count number of group by rows in hibernate with criteria

I want to count the number of group by rows with hibernate Criteria API, but i can only count number of rows aggregated in each group:

ProjectionList projectionList = Projections.projectionList()
        .add(Projections.groupProperty("color"))
        .add(Projections.rowCount());
Criteria criteria = session.createCriteria("ProductEntity");
criteria.setProjection(projectionList);
// adding some criteria
List results = criteria.list();

Above code will results in this query:

select p.color, count(*) from product p group by p.color

But i want this query:

select count(*) from (select p.color from product p group by p.color)

I know it's possible with HQL, but i don't want to use it. So how can i do this with Criteria API?

If you want to know how many different colors are present you should use

Projections.countDistinct("color")

This will result a query which will return the same result as this:

select count(*) from (select p.color from product p group by p.color)

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