78

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?

9
  • 9
    the issue is that you ask for a uniqueResult, meaning there may only be one row returned, but the query finds more than 1 result.
    – Stultuske
    May 26, 2014 at 9:16
  • 7
    but count(*) will always return only 1 row May 26, 2014 at 9:17
  • I just told you what triggers a NonUniqueResultException. I agree that for a count it is weird, but still. have you tried without the UniqueResult constraint?
    – Stultuske
    May 26, 2014 at 9:20
  • What is CustomerData? Abstract class?
    – Perimosh
    Jul 29, 2017 at 12:39
  • 3
    @user3198603 have you resolved the issue? Did you get the reason of problem?
    – cнŝdk
    Aug 28, 2017 at 13:37

16 Answers 16

49

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();

26

Hibernate Optional findTopByClientIdAndStatusOrderByCreateTimeDesc(Integer clientId, Integer status);

"findTop"!! The only one result!

25

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.

3
  • 1
    This should be the accapted answer. And count always return 1, no excuse.
    – Al Kasih
    Aug 3, 2021 at 18:04
  • 1
    This should be the accepted answer. Hibernate is probably doing a UNION with both classes CustomerData and its child. Apr 6, 2023 at 15:23
  • This was the problem I experienced. My solution was to add the class annotation which defines polymorphism=explicit. Feb 14 at 10:43
14

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.

1
7

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

1

Could this exception be thrown during an unfinished transaction, where your application is attempting to create an entity with a duplicate field to the identifier you are using to try find a single entity?

In this case the new (duplicate) entity will not be visible in the database as the transaction won't have, and will never be committed to the db. The exception will still be thrown however.

1

Received this error while doing otherwise correct hibernate queries. The issue was that when having a class extend another hibernate was counting both. This error can be "fixed" by adding a method to your repository class.

By overriding the class count you can manually determine the way this is counted.

@Override 
public Integer count(Page<MyObject> page) {
   // manual counting method here
}
1

I was using JPQL and wanted to return Map. In my case, the reason was that I wanted to get Map<String, String>, but had to expect List<Map<String, String>> :)

1

Check your table, where one entity occurring multiple time's.

I had the same error, with this data :

id amount clientid createdate expiredate
428 100 427 19/11/2021 19/12/2021
464 100 459 22/11/2021 22/12/2021
464 100 459 22/11/2021 22/12/2021

You see here clientid occurring two times with 464.

I solved it by deleting one row :

id amount clientid createdate expiredate
428 100 427 19/11/2021 19/12/2021
464 100 459 22/11/2021 22/12/2021
1

I have found the core of the problem:

result of SELECT COUNT(*) can be a list, if there is a GROUP BY in the query,

and sometimes Hibernate rewrite your HQL and put a GROUP BY into it, just for fun.

0

Basically your query returns more than one result set. In API Docs uniqueResult() method says that Convenience method to return a single instance that matches the query, or null if the query returns no results

uniqueResult() method yield only single resultset

0

Thought this might help to someone, it happens because "When the number of data queries is greater than 1".reference

0

As what Ian Wang said, I suspect you are using a repository from spring. And a few days ago you just copy past a class and forgot to delete it when it is finally unused. Check that repository, and see if there is multiple same class of table you use. The count is not the count of rows, but the count of the table problem.

0

For me the error is caused by spring.jpa.hibernate.ddl-auto=update in application.properties file replacing it with spring.jpa.hibernate.ddl-auto=create solved the issue, but it still depends on your needs to decide which configuration you need in your project, for more insights on the topic check this.

-1

This means that orm technology is not preprogrammed to give you which results you are looking for because there are too many of the same results in the database. for example If there is more than one same value in my database and I want to get it back, you will encounter the error you get with the select query.

1
  • 3
    Your post is unreadable but seems to be an attempt to answer the question. I recommend to edit with some help from a more fluent person to improve this according to How to Answer.
    – Yunnosch
    Oct 12, 2021 at 12:05
-7

First you must test the query list size; here a example:

long count;
if (query.list().size() > 0)
    count=(long) criteria.list().get(0);   
else
    count=0;            
return count;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.