I’m building a query where I want to pass a collection as a parameter:
List<String> items = new LinkedList();
//adding optional items
Query query = s.getNamedQuery("myQueryName").setParameterList("item", items);
My query looks like this:
SELECT i from Item i
//... not important things
WHERE ( i.name in (:item) )
but I want to make it optional, so the items list could be empty. But when it’s empty, I get an exception:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected end of subtree
So I tried to use some functions like:
SELECT i from Item i
//... not important things
WHERE ( (:item) is null or i.name in (:item) )
SELECT i from Item i
//... not important things
WHERE ( (:item) is empty or i.name in (:item) )
SELECT i from Item i
//... not important things
WHERE ( size(:item)=0 or i.name in (:item) )
but none of it seems to work. How can I solve this problem and checking if an item name is in a list only if the list is not empty?
That’s, IMHO, a design problem in SQL, that is of course also present in HQL, since it directly translates to SQL.
There is no easy solution to deal with that in HQL. The easiest, and most efficient thing to do, is to check the list before even generating and executing the query.
In many cases, you just need to do:
In your case, I would use a criteria query (or another API used to dynamically build queries), and build the query dynamically: