Java 我可以将 SQL 的 IN(...) 语句用于 namedQuery 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4489687/
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-08-14 17:59:24  来源:igfitidea点击:

Can I use SQL's IN(...) statement for a namedQuery?

javasqlnamed-query

提问by kamaci

How can I use IN at my namedQuery?

如何在我的 namedQuery 中使用 IN?

@NamedQueries(  
 {   
 @NamedQuery(name = "GetAvailableProducts", query = new StringBuilder("").append("SELECT   p   FROM Product p WHERE p.type= :type AND (p.available IN ('I want to define changeable size of an array or sometinhg like that') OR p.available = :available)")),  
 }

I mean that I can set 'type' parameter (I defined it as a variable----> :type) and I want to define variables inside of IN statement to. However the number of parameters are not constant. I want to define an array or something like that :array[] and I want to set it when I call that namedQuery.

我的意思是我可以设置“type”参数(我将它定义为变量----> :type)并且我想在 IN 语句中定义变量。然而,参数的数量不是恒定的。我想定义一个数组或类似的东西 :array[] 并且我想在调用namedQuery时设置它。

采纳答案by Tadeusz Kopec

NamedQuery

命名查询

@NamedQueries(  
{   
 @NamedQuery(name = "GetAvailableProducts", query = "FROM Product p WHERE p.type= :type AND (p.available IN (:availableCollection) OR p.available = :available)",  
}

Set parameters

设置参数

Hibernate:

休眠

query.setParameterList('availableCollection', yourCollection);

JPA:

JPA:

query.setParameter('availableCollection', yourCollection);

回答by AlexR

Did you try something like

你有没有尝试过类似的东西

SELECT   p   FROM Product p WHERE p.type= :type AND (p.available IN 
('foo', 'bar') OR p.available = :available)

(if "available" is a string)

(如果“可用”是一个字符串)

or

或者

SELECT   p   FROM Product p WHERE p.type= :type AND (p.available IN 
(1, 2, 3) OR p.available = :available)

(if available is a number)?

(如果可用是一个数字)?

回答by Art Licis

Expression 'IN' in JPQL is equal to writing multiple 'OR' statements, in your case an example of 'IN' would be:

JPQL 中的表达式“IN”等于编写多个“OR”语句,在您的情况下,“IN”的示例是:

... p.available IN ('US', 'GB') ...

Which I believe is equal to:

我认为这等于:

... p.available = 'US' OR p.available = 'GB' ...

Here's a link that explains it well: OpenJPA: IN Expression

这是一个解释得很好的链接:OpenJPA: IN Expression

EDITP.S. Assuming p.available is String (character type)

编辑PS 假设 p.available 是字符串(字符类型)

EDIT2The author has edited question so many times that I can't follow up him :) As for the actual question about passing array for IN-expression, here's a link of similar question on StackOverflow: JPQL IN clause - Arrays

EDIT2作者已经编辑了很多次问题,我无法跟进他:) 至于关于为 IN 表达式传递数组的实际问题,这里是 StackOverflow 上类似问题的链接:JPQL IN 子句 - 数组