Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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(); // ERROR THROWN HERE 

Hibernate throws below exception at the marked line:

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?

like image 721
user3198603 Avatar asked May 26 '14 09:05

user3198603


People also ask

What is non unique result exception?

Thrown by the persistence provider when getSingleResult() is executed on a query and there is more than one result from the query. This exception will not cause the current transaction, if one is active, to be marked for roll back.

What is uniqueResult in hibernate?

uniqueResult() Convenience method to return a single instance that matches the query, or null if the query returns no results.


2 Answers

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

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

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

like image 157
GROX13 Avatar answered Nov 05 '22 18:11

GROX13


Hibernate Optional findTopByClientIdAndStatusOrderByCreateTimeDesc(Integer clientId, Integer status);

"findTop"!! The only one result!

like image 40
李凉杰 Avatar answered Nov 05 '22 18:11

李凉杰