使用条件计算hibernate中按行分组的数量

Ary*_*rya 6 java sql hibernate group-by

我想group by用hibernate Criteria API计算行数,但我只计算每个组中聚合的行数:

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();
Run Code Online (Sandbox Code Playgroud)

上面的代码将导致此查询:

select p.color, count(*) from product p group by p.color
Run Code Online (Sandbox Code Playgroud)

但我想要这个查询:

select count(*) from (select p.color from product p group by p.color)
Run Code Online (Sandbox Code Playgroud)

我知道HQL可能,但我不想使用它.那么我如何使用Criteria API执行此操作?

小智 2

如果你想知道有多少种不同的颜色,你应该使用

Projections.countDistinct("color")
Run Code Online (Sandbox Code Playgroud)

这将导致一个查询返回与此相同的结果:

select count(*) from (select p.color from product p group by p.color)
Run Code Online (Sandbox Code Playgroud)