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;
}
asked Aug 7, 2012 at 7:02
Javi Pedrera
2,1054 gold badges21 silver badges29 bronze badges
3 Answers 3
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).
answered Aug 7, 2012 at 7:08
JB Nizet
694k94 gold badges1.3k silver badges1.3k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
using following annotation
@Enumerated (value = EnumType.STRING)
OR
Query q = session.createQuery(from Comment c where c.rating = :rating);
q.setParameter(rating,
Rating.LOW,
Hibernate.custom(RatingUserType.class));
answered Aug 7, 2012 at 7:47
Mohammod Hossain
4,1042 gold badges28 silver badges37 bronze badges
Comments
Here is the example, with two ways.
- First way is to explicitly provide enum
- And a second, more convenient, is to provide a string representation, if a field is enumerated as sring.
public Optional<AffectedAsset> getByEntityId(Long entityId, String assetType) {
String hql = "FROM AffectedAsset a WHERE a.entityId = :entityId "
+ " AND a.type = :assetType "
+ " ORDER BY id DESC";
Query query = getSession().createQuery( hql );
query.setLong( "entityId", entityId );
// little bit cumbersome :
// query.setParameter( "assetType", AffectedAsset.Type.valueOf( assetType.toUpperCase() ) );
// my preferred way :
query.setString( "assetType", assetType.toUpperCase() );
query.setReadOnly( true );
query.setMaxResults( 1 );
AffectedAsset res = (AffectedAsset) query.uniqueResult();
return Optional.ofNullable( res );
}
answered Mar 30, 2021 at 10:10
dobrivoje
1,0122 gold badges12 silver badges19 bronze badges
Comments
lang-java
query.setParameter(1, TypeEnum.X);?