Jpql IN query with enum parameter

I am using a JPQL query to check if a list contains the specified enum values. If the enum value is the only element to check, it's pretty simple.

In the query expression

query = "... where s.status = :status"; 

and then set a 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 (for example, "0,1,2", which means a list of status values)

But I can not find a solution. I also checked with s.status.ordinal() IN (statusList) in the request, but no luck.

I am using a JPA implementation: EclipseLink (JPA 2.0)

The actual name of my entity is 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)); 
+7
source share
1 answer

You cannot compare enums with strings or integers. The constant field is of type Status, which is an enumeration (or at least suppose the type is Status, since you did not specify the class name enum).

So, what you should pass as an argument to the collection in the IN clause is a set of statuses. For example:

 query = "... where s.status IN :statusList"; ... q.setParameter("statusList", EnumSet.of(Status.APPROVED, Status.CLOSED)); 
+12
source

All Articles