我是JPA的新手, 我只想为实体中的属性设置特定的修复部门名称,作为约束的修复字符串。即,属性的默认值。
如何设置?
答案 0 :(得分:1)
我认为最好的选择是使用Dinesh Dontha指示的枚举,请尝试以下操作:
实体
@Entity
public class MyEntity implements Serializable(){
private MyEnum attribute;
}
枚举
public enum MyEnum {
NAME1("N1")
private String shortName;
private MyEnum(String shortName) {
this.shortName = shortName;
}
public String getShortName() {
return shortName;
}
public static MyEnum fromShortName(String shortName) {
switch (shortName) {
case "N1":
return NacionalidadEnum.NAME1;
default:
throw new IllegalArgumentException("ShortName [" + shortName
+ "] not supported.");
}
}
}
转换器
@Converter(autoApply = true)
public class MyEntityEnumConverter implements AttributeConverter<MyEnum, String> {
@Override
public String convertToDatabaseColumn(MyEnum myEnum) {
return myEnum.getShortName();
}
@Override
public MyEnum convertToEntityAttribute(String dbData) {
return MyEnum.fromShortName(dbData);
}
}