This week's book giveaway is in the Jython/Python forum.
We're giving away four copies of Murach's Python Programming and have Michael Urban and Joel Murach on-line!
See this thread for details.
Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

enums in ejb queries  RSS feed

 
Karol Oslowski
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Karol Oslowski
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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,
 
suyog barve
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!