简体   繁体   English

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

[英]Hibernate: Set property field to static final object instance

I would like to create static final instances in my application that I can use to drive logic.我想在我的应用程序中创建静态最终实例,我可以用它来驱动逻辑。 An example of this would be:这方面的一个例子是:

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");

} }

which is then used in然后用于

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

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

    private ChargeStatusType chargeStatusType;

I am having issues saving ChargeResult as Spring / Hibernate does not know what to do with ChargeResult.ChargeStatusType.我在保存 ChargeResult 时遇到问题,因为 Spring/Hibernate 不知道如何处理 ChargeResult.ChargeStatusType。

Besides converting ChargeStatusType to an enum, is there a way to persist ChargeResult with a ChargeStatusType?除了将 ChargeStatusType 转换为枚举之外,还有没有办法用 ChargeStatusType 来持久化 ChargeResult?

Instead of declaring chargeStatusType as a type of ChargeStatusType you can declare it as a String and persist that String then get the value using a static map like so您可以将ChargeStatusType声明为String并保留该String然后使用静态映射获取值,而不是将chargeStatusType声明为chargeStatusType的类型

@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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM