NonUniqueResultException in Hibernate

March 6, 2012 | Programming

Hibernate Persistence

Sometimes we will get the NonUniqueResultException when we tried to get the result-set by executing query using Hibernate.

The following is the stack trace of the exception:

query did not return a unique result: 2
org.hibernate.NonUniqueResultException: query did not return a unique result: 2
at org.hibernate.internal.AbstractQueryImpl.uniqueElement(AbstractQueryImpl.java:899)
at org.hibernate.internal.AbstractQueryImpl.uniqueResult(AbstractQueryImpl.java:890)
at org.bss.dao.SampleDAO.main(SampleDAO.java:84)

This happens because you’re expecting single result out of the query executing and the database returning multiple

Culprit is this line of code:

Object[] amount = (Object[]) query.uniqueResult();

There are 2 ways to solve this:

  1. Make sure your database returns single result either by altering the query or database.
  2. Use other than uniqueResult, if your query returns more than one row in the following way
List resultList = session.createSQLQuery(sql).list();
for (Iterator it = resultList.iterator(); it.hasNext();) {
    Object object = (Object) it.next();
    System.out.println("Value: " + object);
}

Tags: , , ,

Leave a Reply

If you have a Tip, Comment, Article or anything you want to share, please send it to: i@poisure.com