jpql IN query with enum value

sarwar026 picture sarwar026 · Jun 2, 2013 · Viewed 14.6k times · Source

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.

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)

But I can't find a solution. I have also checked with s.status.ordinal() IN (statusList) in query but no luck.

I'm using JPA Implementation: EclipseLink (JPA 2.0)

My Entity's actual name 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));

Answer

JB Nizet picture JB Nizet · Jun 2, 2013

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).

So, what you must pass as argument for the collection in the IN clause is a collection of Status. For example:

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