【问题标题】:How to get the no of records returned in Hql aggregate query without actually returning them [duplicate]如何获取在 Hql 聚合查询中返回的记录数而不实际返回它们[重复]
【发布时间】:2012-03-13 11:33:07
【问题描述】:

可能重复:
Hibernate HQL: Get count of results without actually returning them

我有一个这样的 hql 查询

select new map(t.divisionId as divisionId,t.projectId as projectId,t.roleId as roleId,t.userId as userId, t.reference as reference,t.note as note,sum(t.hoursPlanned) as hoursPlanned,sum(t.hoursUnplanned) as hoursUnplanned,sum(t.hoursPlanned) + sum(t.hoursUnplanned) as total) from TimeSheetsWork t where t.divisionId in :_divisions group by t.divisionId,t.userId,t.projectId,t.roleId

我想获取从此查询返回的记录数(实际上不返回它们)。 Hibenate有没有办法做到这一点?提前致谢

【问题讨论】:

  • thanx Umer,但它告诉使用 Criteria API 但我想通过使用 HQL 来完成它

标签: hibernate hql


【解决方案1】:

如果您真的只需要记录数,那么您可以使用 count 命令而不是在查询中创建地图,例如:

 select count(t.*) from TimeSheetsWork t where t.divisionId in :_divisions group by      
 t.divisionId,t.userId,t.projectId,t.roleId

【讨论】:

  • 感谢迷你。我想要完成的是结果集中返回的记录数。 Session.getCurrentSession().CreateQuery("my Query ").list().size() 可以,但我需要在不实际执行查询的情况下完成它。
【解决方案2】:

使用这个选择(它也应该在 HQL 中工作)

select count(distinct t.divisionId,t.userId,t.projectId,t.roleId) from TimeSheetsWork t where t.divisionId in :_divisions

只有当t.divisionId,t.userId,t.projectId,t.roleId 的列都没有空值时,它才能正常工作。如果其中一些具有空值,您可以作弊并使用此语句(在此示例中,只有 roleId 可以为空):

select count(distinct t.divisionId,t.userId,t.projectId, coalesce(t.roleId, -1)) from TimeSheetsWork t where t.divisionId in :_divisions

(您可以使用任何值代替 -1,但它不能显示为真正的 roleId)。

然后您在 HQL 中使用该查询,您将获得一个包含计数的值作为查询结果。

【讨论】:

    猜你喜欢
    • 2011-01-13
    • 2012-08-25
    • 2016-01-05
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多