Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set collection items for in-clause in jpql?

Is there a possiblity in JPA 2.0 to set a collection for in-clause in jpql-query? (I'm using EclipseLink)

The next example fails:

TypedQuery<Person> q = em.createQuery("select p from Person p where p.name in (?1)", Person.class);

List<String> names = Arrays.asList(new String[] { "Bill Gates", "Steve Jobs" });
// THIS FAILS
q.setParameter(1, names);

List<Person> persons = q.getResultList();
for (Person p: persons) {
    System.out.println(p.getName());
}

Is there another way to do it?

like image 940
Igor Mukhin Avatar asked Oct 07 '10 07:10

Igor Mukhin


People also ask

Can we use subquery in JPQL?

Yes, It is possible to use subquery with IN operator in JPQL.

Which of the following clauses are supported in JPQL?

JPQL can retrieve information or data using SELECT clause, can do bulk updates using UPDATE clause and DELETE clause.

Which of the following methods is used to execute a select JPQL query?

Query createQuery(String name) - The createQuery() method of EntityManager interface is used to create an instance of Query interface for executing JPQL statement.

Which JPQL keyword is used to determine whether a value is an element of a collection in JPA?

This example shows how to use JPQL keyword MEMBER OF to determine whether a value is an element of a collection.


1 Answers

Here is what the JPA 2.0 specification says about IN expressions:

4.6.9 In Expressions

The syntax for the use of the comparison operator [NOT] IN in a conditional expression is as follows:

in_expression ::=
    {state_field_path_expression | type_discriminator} [NOT] IN
        { ( in_item {, in_item}* ) | (subquery) | collection_valued_input_parameter }
in_item ::= literal | single_valued_input_parameter

...

So according to the specification, the correct syntax when passing a collection_valued_input_parameter is without parenthesis:

select p from Person p where p.name in ?1

And this works with EclipseLink.

like image 151
Pascal Thivent Avatar answered Sep 29 '22 10:09

Pascal Thivent