在JPQL中如何设置in子句的集合项?

6

在JPA 2.0中,是否有可能为jpql查询中的in子句设置集合?(我使用的是EclipseLink)

下面的示例会失败:

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

有没有其他方法可以做到这一点?

2个回答

8

以下是 JPA 2.0 规范对 IN 表达式的说明:

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

...

根据规范,传递 collection_valued_input_parameter 时的正确语法不包括括号:
select p from Person p where p.name in ?1

这也适用于EclipseLink。


嗨。我按照你说的做了,但对我没有起作用。我正在使用EclipseLink 2.5.1。 - Fábio Almeida

0

使用 EclipseLink,您需要为参数命名。

Ex.:

TypedQuery<Person> q = em.createQuery("select p from Person p where p.name in :names", Person.class);
List<String> names = Arrays.asList(new String[] { "Bill Gates", "Steve Jobs" });
q.setParameter("names", names);

符号“?”在使用“in”子句时无效。它在EclipseLink 2.5.1中进行了测试。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接