映射枚举类型的Hibernate注解 [英] Mapping enum types with Hibernate Annotations
问题描述
我有我的Java模型枚举类型,我想映射到数据库的表,。我与Hibernate标注工作,我不知道该怎么做。由于我搜索的答案是比较旧,我不知道哪条路是最好的?
I have an enum type on my Java model which I'd like to map to a table on the database. I'm working with Hibernate Annotations and I don't know how to do that. Since the answers I search were rather old, I wonder which way is the best?
在此先感谢
推荐答案
你需要的东西比<一个别的href=\"http://java.sun.com/javaee/5/docs/api/javax/persistence/Enumerated.html\"><$c$c>@Enumerated$c$c>注解?例如,下面的枚举:
Do you need something else than the @Enumerated
annotation? For example, the following enum:
public enum MyEnum {
VALUE1, VALUE2;
}
可以使用并注明是这样的:
Could be used and annotated like this:
private MyEnum myEnum;
@Column(name="myenum")
@Enumerated(EnumType.ORDINAL)
public MyEnum getMyEnum() {
return myEnum
}
您可以指定的枚举应与的 @Enumerated
的 EnumType
枚举属性中的数据库持久化注解。 EnumType.ORDINAL
指定枚举将持续作为一个整数值。在这里, myEnum
设置为 VALUE1
将持续为0, VALUE2
为1,等等。
You can specify how the enum should be persisted in the database with the EnumType
enum property of the @Enumerated
annotation. EnumType.ORDINAL
specifies that the enum will be persisted as an integer value. Here, myEnum
set to VALUE1
would be persisted as 0, VALUE2
as 1, etc.
另一种方法是使用 EnumType.STRING
来指定该枚举将使用该字段设置为枚举值的名称是持久的。因此,适用于previous例如,字段 myEnum
设置为 MyEnum.VALUE1
将持续为 VALUE1
等
The alternative is to use EnumType.STRING
to specify that the enum will be persisted using the name of the enum value that the field is set to. So, applied to the previous example, setting the field myEnum
to MyEnum.VALUE1
will persist as VALUE1
, etc.
这篇关于映射枚举类型的Hibernate注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!