首页 > 解决方案 > 在数据库中存储枚举

问题描述

我被要求创建一个名为 a 的列Typevarchar2(1)其中包含值partialall

那是我在Model.Java中所做的

    @Column(name="TYPE")
    @Enumerated(EnumType.STRING)
    public TypeEnum getType() {
        return type;
    }

    public void setType(TypeEnum type) {
        this.type = type;
    }

这是我的TypeEnum.java

public enum TypeEnum {
    ALL(0, "all"),
    PARTIAL(1, "partial");

    private int code;
    private String value;

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

    public String getValue() {
        return value;
    }

    public int getCode() {
        return code;
    }

    public static TypeEnum getTypeEnum(String value){
        TypeEnum[] types = values();
        for(int i=0; i<types.length; i++){
            TypeEnum type = types[i];
            if(value.equals(type.getValue()))
                return type;
        }
        return null;
    }

}

那么如何在DB中存储TypeEnum来实现varchar2(1)

标签: javadatabasejpa

解决方案


您可以通过实施AttributeConverter<TypeEnum, String>

@Converter
public class TypeEnumConverter implements AttributeConverter<TypeEnum, String> {

    @Override
    public String convertToDatabaseColumn(TypeEnum attribute) {
        return String.valueOf(attribute.getCode());
    }

    @Override
    public TypeEnum convertToEntityAttribute(String dbData) {
        return getTypeEnumFromCode(parseInt(dbData));
    }
}

getTypeEnumFromCode可以类似于您的getTypeEnum方法来实现。

然后,将其定义为

@Column("TYPE")
@Convert(TypeEnumToString.class)
TypeEnum type;

psI 刚刚code从您的枚举中使用,但它也可以是任何其他逻辑。


推荐阅读