Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用条件计算hibernate中的分组行数_Java_Sql_Hibernate_Group By - Fatal编程技术网

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

Java 使用条件计算hibernate中的分组行数,java,sql,hibernate,group-by,Java,Sql,Hibernate,Group By,我想使用hibernate Criteria API计算分组的行数,但我只能计算每个组中聚合的行数: ProjectionList projectionList = Projections.projectionList() .add(Projections.groupProperty("color")) .add(Projections.rowCount()); Criteria criteria = session.createCriteria("Product

我想使用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();
上述代码将导致此查询:

select p.color, count(*) from product p group by p.color
select count(*) from (select p.color from product p group by p.color)
但我想问:

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

我知道使用HQL是可能的,但我不想使用它。那么如何使用Criteria API实现这一点呢?

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

Projections.countDistinct("color")
这将产生一个查询,该查询将返回与以下相同的结果:

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

Pusker的答案仅适用于具有一列的group by查询。我在这里写了一个答案: