[英]Can't pass in List of Enums into Hibernate Query?
I am trying to pass in a list of enums into my hibernate query. 我试图将枚举列表传递到我的休眠查询中。 Here is what I am trying to do:
这是我正在尝试做的事情:
public Integer getReportRunsCount(Set<ReportRunStatus> statusSet, Optional<String> userId) {
Query query = sessionFactory.getCurrentSession().createQuery("select count(1) from ReportRun r where r.status in (:fieldStatuses) and r.createdBy = :userId");
query.setParameterList("fieldStatuses", Arrays.asList(statusSet));
query.setString("userId", userId.orElse(null));
return Ints.checkedCast((Long)query.uniqueResult());
}
ReportRunStatus.java: ReportRunStatus.java:
public enum ReportRunStatus {
STARTED,
QUERYDATA,
PROCESSINGDATA,
COMPLETED,
CANCELLED,
ERROR;
}
I am just trying to pass in these fieldStatuses
as a parameter where ReportRunStatus
is a class of enums. 我只是试图将这些
fieldStatuses
作为参数传递,其中ReportRunStatus
是枚举类。 However, I keep getting this error saying that 但是,我不断收到这个错误,说
java.lang.ClassCastException: java.util.HashSet cannot be cast to java.lang.Enum
Any ideas why this might happen? 任何想法为什么会发生这种情况? I Looked at this link here: using enum list as parameter in HQL query as reference to do what I am trying to do but I keep getting the error above.
我在这里查看了此链接: 使用枚举列表作为HQL查询中的参数作为引用来做我想做的事情,但我一直收到上面的错误。 Any help would be appreciated.
任何帮助,将不胜感激。 Thanks!
谢谢!
What is causing problem is this one: Arrays.asList(statusSet)
造成此问题的原因是:
Arrays.asList(statusSet)
This is simply creating a one-element list, with a Set
as the value (ie a List<Set<ReportRunStatus>>
. However setParameterList
is expecting a Collection<ReportRunStatus>
, hence it caused class cast exception because internally it was getting an element out (which is a HashSet<ReportRunStatus>
) and trying to cast it to a ReportRunStatus
. 这只是创建一个以
Set
为值的单元素列表(即List<Set<ReportRunStatus>>
。但是setParameterList
期望的是Collection<ReportRunStatus>
,因此导致类Collection<ReportRunStatus>
异常,因为在内部它正在获取元素out(这是HashSet<ReportRunStatus>
),然后尝试将其ReportRunStatus
转换为ReportRunStatus
。
What you should do is something like 你应该做的是
query.setParameterList("fieldStatuses", statusSet);
Try this, 尝试这个,
List<String> reportRunStatusList = new ArrayList<String>();
for(ReportRunStatus reportRunStatus : statusSet){
reportRunStatusList.add(reportRunStatus.toString);
}
query.setParameterList("fieldStatuses", reportRunStatusList);
You just needed to convert the enums to String explicitly. 您只需要将枚举显式转换为String。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.