78

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 "?".

Daniel
  • 25,883
  • 17
  • 87
  • 130
  • 2
    Would you mind adding your answer to this question? I know it's an old one, but self-answering your question is not only permitted, it's explicitly encouraged. – Makoto May 07 '15 at 06:47

5 Answers5

158

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);
Daniel
  • 25,883
  • 17
  • 87
  • 130
jpkrohling
  • 13,333
  • 1
  • 33
  • 38
24

in HQL you can use query parameter and set Collection with setParameterList method.

    Query q = session.createQuery("SELECT entity FROM Entity entity WHERE name IN (:names)");
    q.setParameterList("names", names);
michal.kreuzman
  • 11,132
  • 8
  • 53
  • 66
5

Leaving out the parenthesis and simply calling 'setParameter' now works with at least Hibernate.

String jpql = "from A where name in :names";
Query q = em.createQuery(jpql);
q.setParameter("names", l);
Steven Spungin
  • 17,551
  • 4
  • 57
  • 56
3

Using pure JPA with Hibernate 5.0.2.Final as the actual provider the following seems to work with positional parameters as well:

Entity.java:

@Entity
@NamedQueries({
    @NamedQuery(name = "byAttributes", query = "select e from Entity e where e.attribute in (?1)") })
public class Entity {
    @Column(name = "attribute")
    private String attribute;
}

Dao.java:

public class Dao {
    public List<Entity> findByAttributes(Set<String> attributes) {
        Query query = em.createNamedQuery("byAttributes");
        query.setParameter(1, attributes);

        List<Entity> entities = query.getResultList();
        return entities;
    }
}
Attila T
  • 404
  • 3
  • 11
1

query.setParameterList("name", new String[] { "Ron", "Som", "Roxi"}); fixed my issue