使用 Hibernate Annotations 映射枚举类型 [英] Mapping enum types with Hibernate Annotations

查看:31
本文介绍了使用 Hibernate Annotations 映射枚举类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Java 模型上有一个枚举类型,我想将其映射到数据库中的一个表.我正在使用 Hibernate Annotations,但我不知道该怎么做.由于我搜索的答案比较老,不知道哪种方式最好?

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?

提前致谢

推荐答案

除了 @Enumerated 注释?例如,以下枚举:

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 来指定将使用字段设置为的枚举值的名称持久化枚举.因此,应用于前面的示例,将字段 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 Annotations 映射枚举类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆