getSingleResult() 改变 count() 查询
我的应用程序使用 Hibernate 连接到 SQL Server。我最近将 DAO 函数从其中一个表中检索计数从“return query.getResultList().get(0)”更改为“query.getSingleResult()”。 sql count() 查询是通过namedQuery 提供的。
当我进行此更改时,我注意到 Hibernate 生成的 SQL 现在已从 选择计数(test0_.TestId)作为...... 到 select top 2 count(test0_.TestId) as...
为什么 Hibernate 会为 getSingleResult() 转换为 top 2 而不是 top 1? 有没有办法关闭 Hibernate 修改我的 count() 查询以使用 top 2 ?
谢谢
My application uses Hibernate to connect to SQL Server. I recently changed my DAO function that retrieves the count from one of the tables from "return query.getResultList().get(0)" to "query.getSingleResult()". The sql count() query is supplied via namedQuery.
When I made this change, I noticed that the SQL generated by Hibernate has now changed from
select count(test0_.TestId) as .....
to
select top 2 count(test0_.TestId) as...
Why would Hibernate translate to top 2 and not top 1 for getSingleResult()?
Is there a way to turn off Hibernate modifying my count() query to use top 2 ?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Hibernate 选择 2 个条目来检查是否只有一个或多个。如果返回 2,则会抛出异常,因为结果不唯一。如果使用 top 1,Hibernate 将无法判断是否还有更多。
Hibernate selects 2 entries in order to check if there's just one or more. If 2 are returned, it will throw an exception, since the result is not unique. If top 1 was used, Hibernate wouldn't be able to tell if there would be more.
如果不存在一个结果,
getSingleResult
会引发异常。这样它就可以检查是否返回了多行。getSingleResult
throws an exception if there is not exactly one result. This is so it can check if there are more than one rows returned.