SQL JPQL IN 子句:Java 数组(或列表、集合...)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2772305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 06:10:15  来源:igfitidea点击:

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

sqlormjpajpqlnamed-query

提问by Bernd Haug

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)").

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

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?

有没有办法指定一个数组或一个列表(或其他一些容器)应该展开为 IN 子句的值?

回答by Pascal Thivent

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

我不确定 JPA 1.0,但您可以Collection在 JPA 2.0 中传递 a :

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

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

使用 EclipseLInk 测试。使用 Hibernate 3.5.1,您需要用括号将参数括起来:

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

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

但这是一个错误,前面示例中的 JPQL 查询是有效的 JPQL。见HHH-5126

回答by Ashish Thukral

The oracle limit is 1000 parameters. The issue has been resolved by hibernate in version 4.1.7 although by splitting the passed parameter list in sets of 500 see JIRA HHH-1123

oracle 限制为 1000 个参数。该问题已在 4.1.7 版中通过 hibernate 解决,尽管通过将传递的参数列表拆分为 500 组, 请参阅 JIRA HHH-1123