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

Viewed 29881

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;
}
3 Answers

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 );
}
Related