gpt4 book ai didi

hibernate HQL : Get count of results without actually returning them

转载 作者:行者123 更新时间:2023-12-03 06:40:12 24 4
gpt4 key购买 nike

我想获取动态生成的 HQL 查询的结果计数,而不实际获取结果列表。假设我的查询类似于:

select Company company LEFT OUTER JOIN FETCH products product

我在 Hibernate 文档中读到:

You can count the number of query results without returning them:

( (Integer) session.createQuery("select count(*) from ....").iterate().next() ).intValue()

我怀疑我应该用我的查询替换 ....,但这不起作用,因为 HQL 不支持 FROM 中的子选择。

那么,我应该如何统计动态生成的 HQL 查询的结果呢?我认为通过执行它并获取结果列表的 .size() 可能是不必要的开销。

干杯!

**更新:**

我使用这个正则表达式来转换我的查询:

Number num = (Number) em.createQuery(dynamicQuery.replaceAll("select \\w+ from ", "select count(*) from ")).getSingleResult();

我明白了:

Blockquote

EJB Exception: ; nested exception is: java.lang.IllegalArgumentException: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=product,role=org.myCompany.applicant.entity.Applicant.products,tableName=PRS_DEV.PRODUCT,tableAlias=products1_,origin=PRS_DEV.APPLICANT applicant0_,colums={applicant0_.APPLICANT_ID ,className=org.myCompany.product.entity.Product}}] [select count() from org.myCompany.applicant.entity.Applicant applicant LEFT OUTER JOIN FETCH applicant.products product ]; nested exception is: java.lang.IllegalArgumentException: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=product,role=org.myCompany.applicant.entity.Applicant.products,tableName=PRS_DEV.PRODUCT,tableAlias=products1_,origin=PRS_DEV.APPLICANT applicant0_,colums={applicant0_.APPLICANT_ID ,className=org.myCompany.product.entity.Product}}] [select count() from org.myCompany.applicant.entity.Applicant applicant LEFT OUTER JOIN FETCH applicant.products product ]

最佳答案

这应该可以解决问题:

select count(*) FROM Company c JOIN ...

不涉及子选择,只是返回计数,而不是返回Company

编辑: FETCH 现在不合适了。您不会从查询中返回实体,而只会返回计数,因此 Hibernate 会提示。删除它应该会有所帮助:

select count(product) from org.myCompany.applicant.entity.Applicant applicant 
LEFT OUTER JOIN applicant.products product

关于 hibernate HQL : Get count of results without actually returning them,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2198528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com