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:
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. 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. Any help would be appreciated. Thanks!
What is causing problem is this one: 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
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.