Forums Register Login

enums in ejb queries

+Pie Number of slices to send: Send
Dear All,

I'm developing an application in EJB3. I have an entity bean with stored column which value is of enum type. I was wondering how to write a select (@namedquery) where I want to find all fields with value equal to one of the enum values?

Kind Regards,

karol
+Pie Number of slices to send: Send
I found here

a description of solution for my problem:



Using an Enumerated Annotation

Programmers sometimes run into problems when they use an Enumerated annotation in combination with the Java Persistence Query Language.

An Enumerated annotation specifies that a persistent property or field should be persisted as an enumerated type. An enum (the base class for all enumerated types) can be mapped as either a string or an integer. There are two enumerated types: ORDINAL and STRING. If the enumerated type is not specified, the enumerated type is assumed to be ORDINAL.

Problems arise if you try to assign a numeric or string value based on an enum type. For example, in entity class Customer, CustomerStatus is an enum. The field status in Customer, defined as CustomerStatus, is mapped to an integer. You might think that the following Java Persistence Query Language query correctly queries customer status:
String ejbql = "SELECT c FROM Customer c
WHERE c.status = 1";

In fact, the query throws a java.lang.IllegalArgumentException. The exception is thrown because the Java Persistence Query Language compiler is expecting an enum constant.

The correct way to query the customer status is as follows:
// run a Java Persistence query
String ejbql = "SELECT c FROM Customer c
WHERE c.status = :status";
Query query = em.createQuery(ejbql);
query.setParameter(
"status", Customer.CustomerStatus.FULL_TIME);

In the correct query an enum constant, Customer.CustomerStatus.FULL_TIME is assigned to the enum field status.



I don't really like it, is it any way of putting an enum constant directly into a query?

Regards,
+Pie Number of slices to send: Send
Its very easy:
just try like this-->

String ejbql = "SELECT c FROM Customer c WHERE c.status = :status";
Query query = em.createQuery(ejbql);
query.setParameter("status", CustomerStatus.valueOf(customerStatusVar.name()));

where customerStatusVar can be an object having dynamic value.


Regards
Suyog
But how did the elephant get like that? What did you do? I think all we can do now is read this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 4860 times.
Similar Threads
mysql enum to java string
Enum vs Long
Array stuff again...
mysql enum to java string
static import of enum with .* syntax
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 12:34:50.