Hibernate不能与带有@Id和@Convert或@Converter的枚举一起使用(autoApply = true)

时间:2016-01-06 11:52:30

标签: hibernate enums jpa-2.1

有一些

public class SomeDao {
  @Id private MyEnum id;

  public MyEnum getId() { return id; }
}

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

你会得到类似的东西(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]

1 个答案:

答案 0 :(得分:1)

对我来说使用一些虚拟@Id String id_字段(这是Hibernate或JPA所需的,有时/经常(取决于您的方案/映射)不是逻辑上/与模型相关的)很好:

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_;

  ...
}