Hibernate Criteria组的结果计数 - 返回的总分组记录

Out*_*rce 0 hibernate group-by criteria count scrollableresults

我有一个基于Criteria的查询,其中包含以下分组:

Projections.projectionList()
    .add(Property.forName("xyz").group()));
Run Code Online (Sandbox Code Playgroud)

生成的SQL是(专有的,如此清理):

select this_.XYZ as y0_ from FOO.BAR this_ WHERE [long where clause] 
    group by this_.XYZ
Run Code Online (Sandbox Code Playgroud)

现在,从概念上讲,我想用count(*)包装查询结果,以便数据永远不会从数据库返回,只是计数.像这样:

select count(*) from (
  select this_.XYZ as y0_ from FOO.BAR this_ WHERE [long where clause] 
      group by this_.XYZ
)
Run Code Online (Sandbox Code Playgroud)

可能有数千行我不需要,而且我对高性能感兴趣,所以我不希望这些数据来自网络.

我的基于标准的搜索有很多条件.我无法现实地重建它,所以我真的需要坚持使用Criteria.

当然,添加rowCount或count("xyz")并没有帮助,因为它只为每行报告1.

我正在这样做以获得计数:

ScrollableResults scroll = criteria.scroll();
scroll.last();
int count = scroll.getRowNumber();
Run Code Online (Sandbox Code Playgroud)

它有效,但是需要花费很长时间才能重新计算(如果重要的话,在Oracle上).

我可以做我提出的建议吗?

Ken*_*han 7

从概念上讲,

select count(*) from (
  select this_.XYZ as y0_ from FOO.BAR this_ WHERE [long where clause] 
      group by this_.XYZ
)
Run Code Online (Sandbox Code Playgroud)

是相同的

select count(distinct (this_.XYZ)) from FOO.BAR this_ WHERE [long where clause] 
Run Code Online (Sandbox Code Playgroud)

因此,您可以使用Projections.countDistinct((String propertyName))为您的Criteria选择不同的propertyName.

session.createCriteria(Foo.class)
        .add(myOrigianlCriterionObject)
        .setProjection(Projections.countDistinct("XYZ"));
Run Code Online (Sandbox Code Playgroud)