Java 使用条件计算hibernate中的分组行数
我想使用hibernate Criteria API计算分组的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
行数,但我只能计算每个组中聚合的行数:
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查询。我在这里写了一个答案: