JPQL IN 子句:Java 数组(或列表、集合...)? [英] JPQL IN clause: Java-Arrays (or Lists, Sets...)?

查看:19
本文介绍了JPQL IN 子句:Java 数组(或列表、集合...)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我们的数据库中加载所有将文本标记设置为任意少量但任意数量的值的对象.在 SQL 中进行此操作的合乎逻辑的方法是构建一个IN"子句.JPQL 允许 IN,但它似乎要求我直接为 IN 指定每个参数(如in (:in1, :in2, :in3)").

I would like to load all objects that have a textual tag set to any of a small but arbitrary number of values from our database. The logical way to go about this in SQL would be to build an "IN" clause. JPQL allows for IN, but it seems to require me to specify every single parameter to IN directly (as in, "in (:in1, :in2, :in3)").

是否有某种方法可以指定一个数组或一个列表(或其他一些容器),它们应该展开为 IN 子句的值?

Is there some way to specify an array, or a list (or some other container) that should be unrolled to the values of an IN clause?

推荐答案

我不确定 JPA 1.0 是否适用,但您可以在 JPA 2.0 中传递 Collection :

I'm not sure for JPA 1.0 but you can pass a Collection in JPA 2.0:

String qlString = "select item from Item item where item.name IN :names"; 
Query q = em.createQuery(qlString, Item.class);

List<String> names = Arrays.asList("foo", "bar");

q.setParameter("names", names);
List<Item> actual = q.getResultList();

assertNotNull(actual);
assertEquals(2, actual.size());

使用 EclipseLINk 测试.对于 Hibernate 3.5.1,您需要用括号将参数括起来:

Tested with EclipseLInk. With Hibernate 3.5.1, you'll need to surround the parameter with parenthesis:

String qlString = "select item from Item item where item.name IN (:names)";

但这是一个错误,前面示例中的 JPQL 查询是有效的 JPQL.请参阅 HHH-5126.

But this is a bug, the JPQL query in the previous sample is valid JPQL. See HHH-5126.

这篇关于JPQL IN 子句:Java 数组(或列表、集合...)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆