小编典典

Hibernate枚举映射

hibernate

我需要预先将未实现接口的枚举映射到现有数据库,该数据库使用将该枚举存储在与所有者类相同的表中@Enumerated(EnumType.STRING)

class A {
    HasName name;
}

interface HasName {
    String getName();
}

enum X implements HasName {
    John, Mary;

    public String getName() { return this.name(); }
}

enum Y implements HasName {
    Tom, Ann;

    public String getName() { return this.name(); }
}

在这种情况下应如何处理映射?持久化到数据库不会改变,因为实现该接口的所有枚举都将具有不同的值,但是我不确定应如何从数据库中检索对象(我是否需要自定义映射器,它将尝试实例化一个使用指定的enum类进行枚举吗?Hibernate本身是否支持此功能?)。


阅读 216

收藏
2020-06-20

共1个答案

小编典典

可以创建一个自定义UserType(例如this)并从映射中使用它

<property name="type" not-null="true">
  <type name="at.molindo.util.hibernate.EnumUserType">
    <param name="enumClass">
      com.example.MyEnum
    </param>
  </type>
</property>

编辑:Hibernate带有它自己的EnumType(因为在hibernate-annotations中为3.2,因为在hibernate-
core中为3.6-在撰写本文时不知道它在hibernate-annotation中)。

2020-06-20