Java 将序号枚举值设置为从1开始,而不是从0开始
我有一个有三个值的枚举。它被用作实体bean中的属性 下面是bean中的属性:Java 将序号枚举值设置为从1开始,而不是从0开始,java,hibernate,jpa,enums,ordinal,Java,Hibernate,Jpa,Enums,Ordinal,我有一个有三个值的枚举。它被用作实体bean中的属性 下面是bean中的属性: @Enumerated(EnumType.ORDINAL) private BillingMethod billingMethod; 以下是enum类: public enum BillingMethod { ONLINEBILL("enum.billingmethod.onlinebill"), // Should be 1, but is now 0 in the database PAPER
@Enumerated(EnumType.ORDINAL)
private BillingMethod billingMethod;
以下是enum类:
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
不要担心这里的标记
,它用于从属性文件获取字符串表示
那么,如何将序号设置为从1开始而不是从0开始呢?我看到两个选项:
@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或条件进行搜索将无法工作。不太好@Type("com.fully.qualified.class.name.of.MyUserType")
private BillingMethod billingMethod;
(在@type
注释中使用用户类型的完全限定名时,无需注册)
实现起来有点复杂,但在标准枚举映射可以工作的所有情况下都可以工作@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或条件进行搜索将无法工作。不太好@Type("com.fully.qualified.class.name.of.MyUserType")
private BillingMethod billingMethod;
(在@type
注释中使用用户类型的完全限定名时,无需注册)
实现起来有点复杂,但在标准枚举映射可以工作的所有情况下都可以工作我也有同样的问题——看看这里的解决方案,它对我很有效:
作者使用Hibernate用户类型解决这个问题。我用同样的方法实现了它,而且它很有效 我也有同样的问题-看看这里的解决方案,它对我很有效:
作者使用Hibernate用户类型解决这个问题。我用同样的方法实现了它,而且它很有效 请看:@AlexR,这对我不起作用。仍然在数据库中为第一个值保存0,为第二个值保存1。我没有阅读足够的问题。我道歉。这是一种变通方法,允许您使用指定的编号而不是序号。显然,这不适用于您的用例。我错了。看这里:我试过了,它很有效……请看:@AlexR,这对我不起作用。仍然在数据库中为第一个值保存0,为第二个值保存1。我没有阅读足够的问题。我道歉。这是一种变通方法,允许您使用指定的编号而不是序号。显然,这不适用于您的用例。我的错误。看这里:我已经试过了,它很有效…你也可以先引入一个伪枚举值你也可以先引入一个伪枚举值