Hibernate HQL Query : How to set a Collection as a named parameter of a Query?
Asked Answered
O

3

68

Given the following HQL Query:

FROM
    Foo
WHERE
    Id = :id AND
    Bar IN (:barList)

I set :id using the Query object's setInteger() method.

I would like to set :barList using a List of objects, but looking at the Hibernate documentation and list of methods I cannot see an obvious choice of which to use. Any ideas?

Owenism answered 20/2, 2009 at 16:26 Comment(0)
O
93

Use Query.setParameterList(), Javadoc here.

There are four variants to pick from.

Outrage answered 20/2, 2009 at 16:40 Comment(3)
Thank you for pointing this out! I completely overlooked this when looking at the the JavaDoc.Owenism
D: Oh noes, broken link (...painfully typical of the JBoss docs)Firm
That only works if you are using a hibernate Query object, but won't work if you import javax.persistence.Query. Just my two cents.Abramabramo
B
33

I'm not sure about HQL, but in JPA you just call the query's setParameter with the parameter and collection.

Query q = entityManager.createQuery("SELECT p FROM Peron p WHERE name IN (:names)");
q.setParameter("names", names);

where names is the collection of names you're searching for

Collection<String> names = new ArrayList<String();
names.add("Joe");
names.add("Jane");
names.add("Bob");
Buccinator answered 20/2, 2009 at 16:33 Comment(0)
G
1

In TorpedoQuery it look like this

Entity from = from(Entity.class);
where(from.getCode()).in("Joe", "Bob");
Query<Entity> select = select(from);
Gahan answered 1/11, 2011 at 2:25 Comment(2)
How does that answer the question? Please don't post links to your project if they don't address the problem directly.Visser
It generate an hql query with a in conditionGahan

© 2022 - 2024 — McMap. All rights reserved.