Hibernate Criteria group by 结果的计数 - 返回的分组记录总数
我有一个基于条件的查询,具有以下分组:
Projections.projectionList()
.add(Property.forName("xyz").group()));
生成的 SQL 是(专有的,因此经过清理):
select this_.XYZ as y0_ from FOO.BAR this_ WHERE [long where clause]
group by this_.XYZ
现在,从概念上讲,我想用 count(*) 包装查询结果,以便数据永远不会从数据库返回,只是计数。像这样:
select count(*) from (
select this_.XYZ as y0_ from FOO.BAR this_ WHERE [long where clause]
group by this_.XYZ
)
可能有数千行我不需要,并且我对高性能感兴趣,所以我不希望这些数据通过网络传输。
我的基于条件的搜索有很多条件。我无法现实地重建它,所以我真的需要坚持标准。
当然,添加 rowCount 或 count("xyz") 没有帮助,因为它只为每行报告 1。
我目前正在这样做以获得计数:
ScrollableResults scroll = criteria.scroll();
scroll.last();
int count = scroll.getRowNumber();
它有效,但需要很长时间才能返回计数(如果重要的话,在 Oracle 上)。
我可以按照我的建议去做吗?
I have a Criteria-based query with the following grouping:
Projections.projectionList()
.add(Property.forName("xyz").group()));
The SQL generated is (proprietary, so cleansed):
select this_.XYZ as y0_ from FOO.BAR this_ WHERE [long where clause]
group by this_.XYZ
Now, conceptually, I want to wrap the query results with a count(*) such that the data never comes back from the database, just the count. Like this:
select count(*) from (
select this_.XYZ as y0_ from FOO.BAR this_ WHERE [long where clause]
group by this_.XYZ
)
There could be thousands of rows that I don't need and I'm interested in high-performance, so I don't want that data coming over the network.
My Criteria-based search has numerous conditions. I cannot realistically rebuild it, so I really need to stick with Criteria.
Adding rowCount or count("xyz") doesn't help, of course, because it just reports 1 for each row.
I'm currently doing this to get the count:
ScrollableResults scroll = criteria.scroll();
scroll.last();
int count = scroll.getRowNumber();
It works, but it is taking a long time to come back with the count (on Oracle if it matters).
Can I do what I'm proposing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从概念上讲,
与 So 相同
,您可以使用 Projections.countDistinct((String propertyName)) 为您的 Criteria 选择不同的 propertyName 。
Conceptually ,
is the same as
So , you can use
Projections.countDistinct((String propertyName))
to select the distinct propertyName for your Criteria .使用
子查询 API
并创建内部条件。第一个标准是分组依据所包含的主要标准。行数取自第二个标准 100% 保证结果。
第一个标准
第二个标准
Use the
Subqueries API
and create inner criteria.First criteria is the main criteria the group by is included to it. Row count is taken from the second criteria 100% guaranteed result.
First criteria
Second criteria