Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate HQL casting: java.lang.String cannot be cast to java.lang.Enum

Tags:

java

hibernate

I am getting this problem:

java.lang.String cannot be cast to java.lang.Enum

When I try this HQL:

...
query = em.createQuery("SELECT object from Entity object where object.column = ?");
query.setParameter(1, "X");
return query.getResultList();

Where in DB the type is a Varchar2(x) with a check constraint and the variable in the entity is defined with Enum using the tag @Enumerated(EnumType.STRING):

public enum ColumnEnum {
    X, Y;
}
like image 994
Javi Pedrera Avatar asked Aug 07 '12 07:08

Javi Pedrera


1 Answers

If the field is defined as an enum, you must pass an enum as parameter:

query.setParameter(1, TypeEnum.X);

And let Hibernate use the mapping to transform the parameter into a String (if @Enumerated(EnumType.STRING) is uses) or into an int (if @Enumerated(EnumType.ORDINAL) is used).

like image 148
JB Nizet Avatar answered Oct 09 '22 18:10

JB Nizet