org.hibernate.NonUniqueResultException:查询未返回唯一结果:2? [英] org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

查看:505
本文介绍了org.hibernate.NonUniqueResultException:查询未返回唯一结果:2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在dao中有以下代码

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在第1行的异常下方抛出

Hibernate throws below exception at line 1

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

我不确定发生什么情况,因为count(*)总是只返回一行.另外,当我直接在db上运行此查询时,它返回的结果为1.那又是什么问题?

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?

推荐答案

似乎您的查询返回了多个检查数据库的结果.在query.uniqueResult()的文档中,您可以阅读:

It seems like your query returns more than one result check the database. In documentation of query.uniqueResult() you can read:

抛出:org.hibernate.NonUniqueResultException-如果还有更多 多于一个匹配结果

Throws: org.hibernate.NonUniqueResultException - if there is more than one matching result

如果您想避免此错误并仍然使用唯一结果请求,则可以使用这种解决方法query.setMaxResults(1).uniqueResult();

If you want to avoid this error and still use unique result request, you can use this kind of workaround query.setMaxResults(1).uniqueResult();

这篇关于org.hibernate.NonUniqueResultException:查询未返回唯一结果:2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆