Daniel Daniel - 3 months ago 27
Java Question

IN-clause in HQL or Java Persistence Query Language

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

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);