gpt4 book ai didi

java - Hibernate:将属性字段设置为静态最终对象实例

转载 作者:行者123 更新时间:2023-12-01 18:32:10 24 4
gpt4 key购买 nike

我想在我的应用程序中创建静态最终实例,我可以用它来驱动逻辑。一个例子是:

public class ChargeStatusType {

private String code;
private String value;
private ChargeStatusType(String code, String value){
this.code = code;
this.value = value;
}

public static final ChargeStatusType APPROVED = new ChargeStatusType("APPROVED", "Approved");
public static final ChargeStatusType COMPELTED = new ChargeStatusType("COMPLETED", "Completed");
public static final ChargeStatusType CANCELLED = new ChargeStatusType("CANCELLED", "Cancelled");
public static final ChargeStatusType FAILED = new ChargeStatusType("FAILED", "Failed");

}

然后在

中使用
@Entity
@Table(name="charge_result")
public class ChargeResult extends RepresentationModel<ChargeResult> {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;

private ChargeStatusType chargeStatusType;

我在保存 ChargeResult 时遇到问题,因为 Spring/Hibernate 不知道如何处理 ChargeResult.ChargeStatusType。

除了将 ChargeStatusType 转换为枚举之外,还有其他方法可以使用 ChargeStatusType 来持久化 ChargeResult 吗?

最佳答案

无需将 chargeStatusType 声明为 ChargeStatusType 类型,您可以将其声明为 String 并保留该 String > 然后使用静态 map 获取值,如下所示

@Entity
@Table(name="charge_result")
public class ChargeResult extends RepresentationModel<ChargeResult> {
private static final Map<String, String> chargeStatusType;
static{
chargeStatusType = new HashMap<>();
chargeStatusType.put("APPROVED", "Approved");
chargeStatusType.put("COMPLETED", "Completed");
chargeStatusType.put("CANCELLED", "Cancelled");
chargeStatusType.put("FAILED", "Failed");
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;

@Column
private String chargeStatusKey;

public String getChargeStatusKey(){
return chargeStatusType.get(chargeStatusKey);
}

关于java - Hibernate:将属性字段设置为静态最终对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60141938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com