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(
at org.hibernate.internal.AbstractQueryImpl.uniqueResult(
at org.bss.dao.SampleDAO.main(

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