开发者

getSingleResult() alters the count() Query

开发者 https://www.devze.com 2023-04-01 11:08 出处:网络
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.getSi

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 modify开发者_运维技巧ing my count() query to use top 2 ?

Thanks


Why would Hibernate translate to top 2 and not top 1 for getSingleResult()?

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 throws an exception if there is not exactly one result. This is so it can check if there are more than one rows returned.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号