简体   繁体   English

使用条件对休眠中的分组行数进行计数

[英]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: 我想用休眠标准API计算group bygroup by的数量,但我只能计算每个组中汇总的行数:

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. 我知道使用HQL是可能的,但是我不想使用它。 So how can i do this with Criteria API? 那么如何使用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)

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

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