IN-clause in HQL or Java Persistence Query Language

Daniel picture Daniel · Jan 28, 2011 · Viewed 146.7k times · Source

I have the following parametrised JPA, or Hibernate, query:

SELECT entity FROM Entity entity WHERE name IN (?)

I want to pass the parameter as an ArrayList<String>, is this possible? Hibernate current tells me, that

java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.String

Is this possible at all?

ANSWER: Collections as parameters only work with named parameters like ":name", not with JDBC style parameters like "?".

Answer

jpkrohling picture jpkrohling · Jan 28, 2011

Are you using Hibernate's Query object, or JPA? For JPA, it should work fine:

String jpql = "from A where name in (:names)";
Query q = em.createQuery(jpql);
q.setParameter("names", l);

For Hibernate's, you'll need to use the setParameterList:

String hql = "from A where name in (:names)";
Query q = s.createQuery(hql);
q.setParameterList("names", l);