问题描述
我需要将未预先实现接口的枚举映射到现有数据库,该数据库使用@Enumerated(EnumType.STRING)
将枚举存储在与所有者类相同的表中.
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(); }
}
在这种情况下应该如何处理映射?坚持到数据库不会改变,因为实现接口的所有枚举都有不同的值,但我不确定应该如何从数据库中检索对象(我是否需要一个自定义映射器,它会尝试实例化一个使用指定的枚举类进行枚举?Hibernate 是否原生支持此功能?).
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?).
推荐答案
可以创建自定义的 UserType
(例如 这个) 并从你的映射中使用它
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>
Hibernate 带有它自己的 EnumType(从 3.2 在 hibernate-annotations 中开始,因为在 hibernate-core 中是 3.6 - 在撰写本文时不知道它在 hibernate-annotations 中,但请参阅 迭戈的回答).
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).
这篇关于休眠枚举映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!