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

查看:146
本文介绍了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天全站免登陆