Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with making a query when using Enum in entity

I have the following in a Question entity:

@NamedQuery(name = "Question.allApproved",     query = "SELECT q FROM Question q WHERE q.status = 'APPROVED'") 

and

@Enumerated(EnumType.STRING) private Status status;  // usual accessors 

I am getting this exception:

Exception Description: Error compiling the query [Question.countApproved: SELECT COUNT(q) FROM Question q WHERE q.status = 'APPROVED'], line 1, column 47: invalid enum equal expression, cannot compare enum value of type [myCompnay.application.Status] with a non enum value of type [java.lang.String]. at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:501)

How do I fix this?

like image 787
LuckyLuke Avatar asked Nov 21 '11 19:11

LuckyLuke


People also ask

Why is enum not good?

It's hard to voice what your actual needs are to a potential partner for fear that they may write you off. Transparency requires over communication. If your communication skills are already not that great, ENM is going to be more of a headache than an opportunity to be your most authentic self.

What annotation is used if enum is used in an entity?

The most common option to map an enum value to and from its database representation in JPA before 2.1 is to use the @Enumerated annotation.

Are enums bad practice?

Many people consider Enums as a code smell and an anti-pattern in OOPs. Certain books have also cited enums as a code smell, such as the following. In most cases, enums smell because it's frequently abused, but that doesn't mean that you have to avoid them. Enums can be a powerful tool in your arsenal if used properly.

Should you store enum in database?

By keeping the enum in your database, and adding a foreign key on the table that contains an enum value you ensure that no code ever enters incorrect values for that column. This helps your data integrity and is the most obvious reason IMO you should have tables for enums.


1 Answers

I think you should use your (fully qualified) Status enum instead of literal value, so something like this: (assuming your Status enum is in com.myexample package)

@NamedQuery(name = "Question.allApproved",              query = "SELECT q                       FROM Question q                       WHERE q.status = com.myexample.Status.APPROVED"). 
like image 130
Piotr Nowicki Avatar answered Sep 20 '22 12:09

Piotr Nowicki