java 带有枚举值的 jpql IN 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16881151/
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
jpql IN query with enum value
提问by sarwar026
I am using JPQL query to check whether the list contains the specified enum values. If the enum value is a single element to check then it is pretty simple.
我正在使用 JPQL 查询来检查列表是否包含指定的枚举值。如果枚举值是要检查的单个元素,那么它非常简单。
In query expression,
在查询表达式中,
query = "... where s.status = :status";
and then set parameter like
然后设置参数,如
query.setParameter("status", statusValue);
But I want to check something like below
但我想检查以下内容
query = "... where s.status IN (:statusList)";
where statusList
is a string of numbers (e.g. "0,1,2" which means the list of the values of status)
其中statusList
是一串数字(例如“0,1,2”表示状态值的列表)
But I can't find a solution. I have also checked with s.status.ordinal() IN (statusList)
in query but no luck.
但我找不到解决办法。我也检查s.status.ordinal() IN (statusList)
过查询但没有运气。
I'm using JPA Implementation: EclipseLink (JPA 2.0)
我正在使用 JPA 实现:EclipseLink (JPA 2.0)
My Entity's actual name is SType
我的实体的实际名称是 SType
public enum SType
{
REQUISITION,
PURCHASE,
FINISHED,
// others
RETURN;
}
QUERY:
询问:
String querySt = "select s.slipType.slipNameSt,s.slipNumberSt, s.idNr from Slip s
where s.slipType.sType IN (:enumTypeListt)";
em.createQuery(querySt).setParameter("enumTypeList", EnumSet.of(SType.REQUISITION,
SType.PURCHASE));
回答by JB Nizet
You can't compare enums with strings or integers. The persistent field is of type Status, which is an enum (or at least, let's suppose the type is Status, since you didn't specify the name of the enum class).
您不能将枚举与字符串或整数进行比较。持久字段的类型是 Status,它是一个枚举(或者至少,假设类型是 Status,因为您没有指定枚举类的名称)。
So, what you must pass as argument for the collection in the IN
clause is a collection of Status. For example:
因此,您必须作为IN
子句中集合的参数传递的是 Status 的集合。例如:
query = "... where s.status IN :statusList";
...
q.setParameter("statusList", EnumSet.of(Status.APPROVED, Status.CLOSED));