我想用 hibernate Criteria API 计算 group 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();
上面的代码将产生这个查询:
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)
关于java - 使用条件计算 hibernate 中按行分组的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27844524/