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?
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.
uniqueResult() Convenience method to return a single instance that matches the query, or null if the query returns no results.
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();
Hibernate Optional findTopByClientIdAndStatusOrderByCreateTimeDesc(Integer clientId, Integer status);
"findTop"!! The only one result!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With