简体   繁体   中英

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.

Besides converting ChargeStatusType to an enum, is there a way to persist ChargeResult with a ChargeStatusType?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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