13

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
2
  • 2
    Shouldn't it be query.setParameter(1, TypeEnum.X); ? Commented Aug 7, 2012 at 7:10
  • I have tried this too, but the received error is the same Commented Aug 7, 2012 at 7:14

3 Answers 3

24

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
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.