将序号枚举值设置为从 1 而不是 0 开始
Setting Ordinal Enum values to start from 1 instead of 0
我有一个包含三个值的枚举。它在实体 bean 中用作 属性。
这是 bean 中的 属性:
@Enumerated(EnumType.ORDINAL)
private BillingMethod billingMethod;
这是枚举 class:
public enum BillingMethod {
ONLINEBILL("enum.billingmethod.onlinebill"), // Should be 1, but is now 0 in the database
PAPERBILL("enum.billingmethod.paperbill"), // Should be 2, but is now 1 in the database
PRINT("enum.billingmethod.print"); // Should be 3, but is now 2 in the database
private String tag;
private BillingMethod(String tag){
this.tag = tag;
}
@Override
public String getTag() {
return tag;
}
}
我需要这些值为 1、2、3 而不是数据库中通常的 0、1、2 是一个非常罕见的特定原因。
不用担心这里的tag
,它是用来从属性文件中获取字符串表示的。
那么,如何将 ORDINAL 设置为从 1 而不是 0 开始?
我看到两个选项:
最简单:为休眠映射一个 Integer,对 getter 中的枚举进行解码:
@Column(...)
private Integer billingMethod;
public BillingMethod getBillingMethod() {
// add here better error handling (logging additional info
// to help diagnose array out of bound exceptions).
return BillingMethod.values()[billingMethod - 1];
}
// add a setter doing a similar thing
问题是如果不进行同样的编码/解码,使用 hql 或标准进行搜索将无法工作。不太好。
创建自定义 UserType。 reference documentation
中的更多信息
然后这样映射字段:
@Type("com.fully.qualified.class.name.of.MyUserType")
private BillingMethod billingMethod;
(在@Type
注解中使用用户类型的完全限定名时,不需要注册)
实现起来有点复杂,但在标准枚举映射可以工作的所有情况下都可以工作
我遇到了同样的问题 - 在这里查看对我有用的解决方案:
Better Enum Mapping with Hibernate
作者使用 Hibernate-UserTypes 来解决这个问题。我以同样的方式实现了它并且有效!
我有一个包含三个值的枚举。它在实体 bean 中用作 属性。
这是 bean 中的 属性:
@Enumerated(EnumType.ORDINAL)
private BillingMethod billingMethod;
这是枚举 class:
public enum BillingMethod {
ONLINEBILL("enum.billingmethod.onlinebill"), // Should be 1, but is now 0 in the database
PAPERBILL("enum.billingmethod.paperbill"), // Should be 2, but is now 1 in the database
PRINT("enum.billingmethod.print"); // Should be 3, but is now 2 in the database
private String tag;
private BillingMethod(String tag){
this.tag = tag;
}
@Override
public String getTag() {
return tag;
}
}
我需要这些值为 1、2、3 而不是数据库中通常的 0、1、2 是一个非常罕见的特定原因。
不用担心这里的tag
,它是用来从属性文件中获取字符串表示的。
那么,如何将 ORDINAL 设置为从 1 而不是 0 开始?
我看到两个选项:
最简单:为休眠映射一个 Integer,对 getter 中的枚举进行解码:
@Column(...) private Integer billingMethod; public BillingMethod getBillingMethod() { // add here better error handling (logging additional info // to help diagnose array out of bound exceptions). return BillingMethod.values()[billingMethod - 1]; } // add a setter doing a similar thing
问题是如果不进行同样的编码/解码,使用 hql 或标准进行搜索将无法工作。不太好。
创建自定义 UserType。 reference documentation
中的更多信息然后这样映射字段:
@Type("com.fully.qualified.class.name.of.MyUserType") private BillingMethod billingMethod;
(在
@Type
注解中使用用户类型的完全限定名时,不需要注册)实现起来有点复杂,但在标准枚举映射可以工作的所有情况下都可以工作
我遇到了同样的问题 - 在这里查看对我有用的解决方案:
Better Enum Mapping with Hibernate
作者使用 Hibernate-UserTypes 来解决这个问题。我以同样的方式实现了它并且有效!