Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String JPA将枚举映射到不同的字符串_String_Jpa_Mapping - Fatal编程技术网

String JPA将枚举映射到不同的字符串

String JPA将枚举映射到不同的字符串,string,jpa,mapping,String,Jpa,Mapping,在我的数据库中有固定的字符串代码(如“200”),我想将其映射到枚举常量,我希望这些常量的名称更易于理解(如“STATUS\u CODE\u OK”)。所以我想将枚举常量映射到数据库中的不同字符串 我认为不可能使用@Enumerated(EnumType.STRING),因为它使用Enum.name(),它返回的枚举常量与声明的枚举常量完全相同,并且是最终的(因此我无法覆盖它) 有什么方法可以绘制它吗?在这里享受最佳实践: 你的实体 @Entity public class MyEntity {

在我的数据库中有固定的字符串代码(如“200”),我想将其映射到枚举常量,我希望这些常量的名称更易于理解(如“STATUS\u CODE\u OK”)。所以我想将枚举常量映射到数据库中的不同字符串

我认为不可能使用
@Enumerated(EnumType.STRING)
,因为它使用
Enum.name()
,它返回的枚举常量与声明的枚举常量完全相同,并且是最终的(因此我无法覆盖它)


有什么方法可以绘制它吗?

在这里享受最佳实践:

你的实体

@Entity
public class MyEntity {

    @Column
    protected String status;

    public Status getStatus() {
        return Status.fromId(status);
    }

    public void setStatus(Status status) {
        this.status = status == null ? null : status.getId();
    }
}
状态枚举代码

public enum Status {
    OK("200"), NOT_OK("500");

    protected String id;

    Status(String id) {
        this.id = id;
    }

    public static Status fromId(String id){
        if (id == null) return null;
        else if (OK.id.equals(id)) return OK;
        else if (NOT_OK.id.equals(id)) return NOT_OK;
        else throw new IllegalArgumentException("Can't parse Status from id : " + id);
    }

}
如您所见,您可以在代码中使用枚举操作,并在数据库中存储字符串值。

我找到了两种解决方案:1)使用EclipseLink
@Convert
注释或2)使用实体侦听器和方法,并使用注释
@PrePersist
@PostLoad
。但是第一个解决方案依赖于JPA实现,第二个解决方案需要实体中的重复字段。这看起来好多了。谢谢