Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLGrammarException when setting empty set as SQL IN parameter

My code causes a SQLGrammarException when I set an empty set into a SQL IN parameter:

Query query = this.entMngr.createNativeQuery("SELECT foo_id, first, last FROM foo WHERE bar IN :barSet");
//barSet is a Set<Integer>
query.setParameter("barSet", barSet);
//this throws exception
List<Object> nativeList =  query.getResultList();

Everything works when the set is not empty. How can I make this agnostic of whether the set (or any collection submitted) is populated or not?

like image 694
amphibient Avatar asked May 07 '15 18:05

amphibient


1 Answers

The problem here is that SQL syntax doesn't allow empty IN clause. So in your case, barSet should not be empty. But you can simply add null to the collection before passing it to the query:

barSet.add(null);
query.setParameter("barSet", barSet);

You can read about this trick here: SQL In Clause with Zero to Many Parameters

like image 63
dened Avatar answered Nov 10 '22 15:11

dened