Java 使用 Hibernate Annotations 映射枚举类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2569053/
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
Mapping enum types with Hibernate Annotations
提问by Thiago
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?
我的 Java 模型上有一个枚举类型,我想将其映射到数据库上的表。我正在使用 Hibernate Annotations,但我不知道该怎么做。由于我搜索的答案很旧,我想知道哪种方式最好?
Thanks in advance
提前致谢
采纳答案by Pascal Thivent
Do you need something else than the @Enumerated
annotation? For example, the following enum:
除了@Enumerated
注释,您还需要其他东西吗?例如,以下枚举:
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
}
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
enum 属性指定应如何将枚举保留在数据库中@Enumerated
。EnumType.ORDINAL
指定枚举将作为整数值持久化。在这里,myEnum
设置VALUE1
为 0、1VALUE2
等。
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.
另一种方法是使用EnumType.STRING
字段设置的枚举值的名称来指定枚举将被持久化。因此,应用于前面的示例,将字段设置myEnum
为MyEnum.VALUE1
将保留为VALUE1
等。