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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:20:38  来源:igfitidea点击:

Mapping enum types with Hibernate Annotations

javahibernateormannotationsenums

提问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 @Enumeratedannotation? 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 EnumTypeenum property of the @Enumeratedannotation. EnumType.ORDINALspecifies that the enum will be persisted as an integer value. Here, myEnumset to VALUE1would be persisted as 0, VALUE2as 1, etc.

您可以使用注释的EnumTypeenum 属性指定应如何将枚举保留在数据库中@EnumeratedEnumType.ORDINAL指定枚举将作为整数值持久化。在这里,myEnum设置VALUE1为 0、1VALUE2等。

The alternative is to use EnumType.STRINGto 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 myEnumto MyEnum.VALUE1will persist as VALUE1, etc.

另一种方法是使用EnumType.STRING字段设置的枚举值的名称来指定枚举将被持久化。因此,应用于前面的示例,将字段设置myEnumMyEnum.VALUE1将保留为VALUE1等。