Search code examples
javahibernatecriteriaprojectionindexoutofboundsexception

criteria.setProjection(Projections.rowCount()) returns empty list


i'm getting a java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 sometimes when executing this code:

Criteria crResult = getSession().createCriteria(XXX.class);
[...]
crResult.setProjection(Projections.rowCount());
Integer countResults = ((Integer)crResult.list().get(0)); // <---This gives the error

Is there any case in that crResult.list() can return an empty list?

(Just a clarification, i'm not talking about receiving a list with an occurrence of 0 results, i'm talking about receiving an empty list)

Thank you!


Solution

  • In that case you can just use:

    crResult.uniqueResult()
    

    I dont think you can get a null list, but you can get a list with 0 items in some cases, in which there is no .get(0) index and throwing the error you're getting...

    You can also just check the list length first then get the item:

    List<?> list= crResult.list();
    if(list.size>0)
        countResults = (Integer)list().get(0);