Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jpql IN query with enum value

Tags:

java

enums

jpql

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));
like image 657
sarwar026 Avatar asked Jun 02 '13 08:06

sarwar026


People also ask

How do I map an enum to a column in a database?

To map the Enum to a String database column type, you need to specify the EnumType. STRING value when using the @Enumerated annotation. As expected, the String representation of the Java Enum was used to populate the associated database column value.

What does enum valueOf return?

valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)

What is the use of @enumerated annotation?

Annotation Type Enumerated. Specifies that a persistent property or field should be persisted as a enumerated type. The Enumerated annotation may be used in conjunction with the Basic annotation, or in conjunction with the ElementCollection annotation when the element collection value is of basic type.


1 Answers

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));
like image 102
JB Nizet Avatar answered Oct 16 '22 20:10

JB Nizet