Hibernate枚举映射 [英] Hibernate enum mapping

查看:102
本文介绍了Hibernate枚举映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将未实现接口的枚举映射到现有的数据库,该数据库使用 @Enumerated(EnumType.STRING)

  class A {
HasName name;
}

接口HasName {
String getName();
}

枚举X实现HasName {
John,Mary;

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

枚举Y实现HasName {
Tom,Ann;

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

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

解决方案

可以创建一个自定义的 UserType (例如这一个),并使用您的映射

 < property name =typenot-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-核心 - 在撰写本文时不了解它在休眠注释中,但请参阅 Diego的答案)。 / p>

I need to map the enums which didn't implement the interface beforehand to the existing database, which stores enums in the same table as the owner class using the @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(); }
}

How the mapping should be handled in this case? Persisting to the database doesn't change as all of the enums implementing the interface will have different values, but I'm not sure how the objects should be retrieved from the DB (do I need a custom mapper, which will try to instantiate an enum using the specified enum classes? Does Hibernate natively support this functionality?).

解决方案

It's possible to create a custom UserType (e.g. this one) and use it from your mappings

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

EDIT: Hibernate comes with it's own EnumType (since 3.2 in hibernate-annotations, since 3.6 in hibernate-core - didn't know about it being in hibernate-annotations at the time of writing, but see Diego's answer).

这篇关于Hibernate枚举映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆