java - 在数据库中存储枚举
问题描述
我被要求创建一个名为 a 的列Type
,varchar2(1)
其中包含值partial
或all
那是我在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)
解决方案
您可以通过实施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
从您的枚举中使用,但它也可以是任何其他逻辑。
推荐阅读
- django - 如何覆盖ckeditor Django的div包装类?
- android - 文本字段 - LazyColum jetpack compose 中的文本低于 IME
- svg - 为什么这个 SVG 投影过滤器在路径很短时会剪切路径?
- javascript - 如何从数组中一次获取一个对象?
- excel - Excel RibbonX 读取编辑框值
- javascript - 图表js插件注释在vue中不起作用
- java - 如何从不同的类调用对象?
- bash - 通过定义标题的正则表达式拆分 Markdown 文本文件
- hash - Ansible 创建 sha512-pbkdf2 哈希
- python - 通过套接字 python 发送不正确的布尔值