Java 休眠枚举映射
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1593929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate enum mapping
提问by dm3
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)
.
我需要将没有预先实现接口的枚举映射到现有数据库,该数据库使用@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?).
在这种情况下应该如何处理映射?坚持到数据库不会改变,因为实现接口的所有枚举都有不同的值,但我不确定应该如何从数据库中检索对象(我是否需要一个自定义映射器,它会尝试实例化一个使用指定的枚举类进行枚举?Hibernate 是否原生支持此功能?)。
采纳答案by sfussenegger
It's possible to create a custom UserType
(e.g. this one) and use it from your mappings
可以创建一个自定义UserType
(例如这个)并从您的映射中使用它
<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 带有它自己的 EnumType(从 hibernate-annotations 中的 3.2 开始,因为 hibernate-core 中的 3.6 - 在撰写本文时不知道它在 hibernate-annotations 中,但请参阅Diego 的答案)。
回答by Diego Pino
Hibernate provides org.hibernate.type.EnumType
to map Enumerated types. For instance,
Hibernate 提供org.hibernate.type.EnumType
映射枚举类型。例如,
package com.igalia.enumerates;
public enum Status {
BUSY,
AVAILABLE;
}
package com.igalia.entities;
class MyClass {
private Status status;
}
Then, do your Hibernate mapping as follows:
然后,按如下方式进行 Hibernate 映射:
<class name="MyClass">
<id name="id">
<generator class="native"/>
</id>
<property name="status">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">com.igalia.enumerates.Status</param>
</type>
</property>
</class>
And that's it. If you prefer to use JPA annotations instead of hbm.xml, use @Enumerated(EnumType.STRING). Check it here:
就是这样。如果您更喜欢使用 JPA 注释而不是 hbm.xml,请使用 @Enumerated(EnumType.STRING)。在这里检查: