Search code examples
hibernateenumsjpa-2.1

Hibernate does not work with enums with @Id and @Convert or @Converter(autoApply=true)


with some

public class SomeDao {
  @Id private MyEnum id;

  public MyEnum getId() { return id; }
}

@Converter( autoApply=true )
public MyEnumConv { ... }

you will get something similar to (JPA 2.1/Hibernate 4.3.7):

org.postgresql.util.PSQLException: Unzulässiger Wert für den Typ int : enumDbStrX.
    at org.postgresql.jdbc2.AbstractJdbc2ResultSet.toInt(AbstractJdbc2ResultSet.java:2955) ~[postgresql-9.3-1102-jdbc41.jar:na]
    at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getInt(AbstractJdbc2ResultSet.java:2138) ~[postgresql-9.3-1102-jdbc41.jar:na]
    at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getInt(AbstractJdbc2ResultSet.java:2589) ~[postgresql-9.3-1102-jdbc41.jar:na]
    at com.mchange.v2.c3p0.impl.NewProxyResultSet.getInt(NewProxyResultSet.java:2426) ~[c3p0-0.9.2.1.jar:0.9.2.1]
    at org.hibernate.type.EnumType$OrdinalEnumValueMapper.getValue(EnumType.java:372) ~[hibernate-core-4.3.7.Final.jar:4.3.7.Final]
    at org.hibernate.type.EnumType.nullSafeGet(EnumType.java:107) ~[hibernate-core-4.3.7.Final.jar:4.3.7.Final]
    at org.hibernate.type.CustomType.nullSafeGet(CustomType.java:127) ~[hibernate-core-4.3.7.Final.jar:4.3.7.Final]
    at org.hibernate.type.AbstractType.hydrate(AbstractType.java:106) ~[hibernate-core-4.3.7.Final.jar:4.3.7.Final]
    at org.hibernate.loader.Loader.extractKeysFromResultSet(Loader.java:785) ~[hibernate-core-4.3.7.Final.jar:4.3.7.Final]
    at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:721) ~[hibernate-core-4.3.7.Final.jar:4.3.7.Final]
    at org.hibernate.loader.Loader.processResultSet(Loader.java:953) ~[hibernate-core-4.3.7.Final.jar:4.3.7.Final]
    at org.hibernate.loader.Loader.doQuery(Loader.java:921) ~[hibernate-core-4.3.7.Final.jar:4.3.7.Final]
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355) ~[hibernate-core-4.3.7.Final.jar:4.3.7.Final]
    at org.hibernate.loader.Loader.doList(Loader.java:2554) ~[hibernate-core-4.3.7.Final.jar:4.3.7.Final]

Solution

  • for me using some dummy @Id String id_ field (which is required by Hibernate or JPA and sometimes/often (depends on your scenarios/mappings) not logically/model-related necessary) works just fine:

    public class SomeDao {
    
      //@Id @Convert( converter=MyEnumConv.class )  // explicitely providing converter 
                                                    // would not help
      @Column( insertable=false, updatable=false)   // necessary because of conflict 
                                                    // with id_ dummy field
      private MyEnum id;
    
      /** @deprecated use {@link #id} instead ; workaround for missing @Id-enum
        *                                       mapping in Hibernate 
        */
      private @Deprecated @Id @Column(name="id") String id_;
    
      ...
    }