org.hibernate.NonUniqueResultException: query did

2020-05-19 04:36发布

I have below code in my dao

String sql = "SELECT COUNT(*) FROM CustomerData WHERE custId = :custId AND deptId = :deptId";

Query query = session.createQuery(sql);
query.setParameter("custId", custId);
query.setParameter("deptId", deptId);
long count =(long) query.uniqueResult(); //line 1

Hibernate throws below exception at line 1

    org.hibernate.NonUniqueResultException: query did not return a unique result: 

I am not sure whats happening as count(*) will always return only one row. Also when i run this query on db directly, it return result as 1. So whats the issue?

9条回答
家丑人穷心不美
2楼-- · 2020-05-19 05:05

Generally This exception is thrown from Oracle when query result (which is stored in an Object in your case), can not be cast to the desired object. for example when result is a

List<T>

and you're putting the result into a single T object.

In case of casting to long error, besides it is recommended to use wrapper classes so that all of your columns act the same, I guess a problem in transaction or query itself would cause this issue.

查看更多
一纸荒年 Trace。
3楼-- · 2020-05-19 05:06

It means that the query you wrote returns more than one element(result) while your code expects a single result.

查看更多
Emotional °昔
4楼-- · 2020-05-19 05:10

I don't think other answers explained the key part: why "COUNT(*)" returns more than one result?

I just encountered the same issue today, and what I found out is that if you have another class extending the target mapped class (here "CustomerData"), Hibernate will do this magic.

Hope this will save some time for other unfortunate guys.

查看更多
登录 后发表回答