【问题标题】:Count number of group by rows in hibernate with criteria使用条件计算休眠中按行分组的数量
【发布时间】:2015-01-08 16:08:58
【问题描述】:

我想用 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 做到这一点?

【问题讨论】:

标签: java sql hibernate group-by


【解决方案1】:

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

Projections.countDistinct("color")

这将产生一个查询,该查询将返回与此相同的结果:

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

【讨论】:

    猜你喜欢
    • 2019-02-19
    • 2018-06-20
    • 2019-08-21
    • 1970-01-01
    • 2012-12-21
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多