1

I am having an issue with Hibernate Criteria when using Restrictions.in.. If the list sent to the restriction doesn't have any values in it then it throws SQL GrammerException which is expected because query would look something like

select * from Person p where p.id in ()

error on Hibernate logs---

com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near ')'. at         
com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError   
SQLServerException.java:197)

error on Spring logs...

org.hibernate.exception.SQLGrammarException: could not execute query
org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
org.hibernate.loader.Loader.doList(Loader.java:2536)
org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276
org.hibernate.loader.Loader.list(Loader.java:2271
org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:119
org.hibernate.impl.SessionImpl.list(SessionImpl.java:1716
org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)

And the code that is causing it is

     criteria.add(Restrictions.in("id", idList)); 

I tried doing this, but it will return all the values in the table, which is completely opposite of what I want.. when the list size is 0 don't return anything..

    if(idList.size()>0  
           criteria.add(Restrictions.in("id", idList)); 

So what changes should I make here so that I get no results from the query when list doesn't have any values in it instead of the exceptions... Thanks in advance!

RKodakandla
  • 3,318
  • 13
  • 59
  • 79

1 Answers1

2

Wrap the entire Criteria in an if-then statement. If the idList is null or idList.size() == 0, don't even bother running the query.

atrain
  • 9,139
  • 1
  • 36
  • 40