jpa 中默认自带了@enumerated 注解,它默认提供了两种形式 string 和 ordinal,表示按照枚举的名字和枚举值的顺序 ,但是有时候我们需要自定义枚举映射,比如枚举的值不是枚举的名字,而是枚举的某个属性值。
这时候我们可以使用@convert 注解来实现自定义枚举映射。
使用默认的@enumerated 注解实现字段映射
@entity
public class user{
@id
private integer userid;
private string name;
private integer age;
@enumerated(string)
private status status;
}
public enum status{
active,deleted,baned
}
使用自定义枚举映射
创建一个用于映射的枚举
public enum status{
active(1),deleted(0),baned(-1);
private final int value;
public int getvalue(){
return this.value;
}
public static status of(int value){
for(status status:status.values()){
if(status.getvalue() == value){
return status;
}
}
throw new illegalargumentexception("invalid value: "+value);
}
}
实现一个枚举转换器
//@converter(autoapply=true) 设置了这个注解,在下面的entity 的例子中就可以省略 @convert
public class statusconverter implements attributeconverter<status,integer>{
@override
public integer converttodatabasecolumn(status attribute){
return attribute.getvalue();
}
@override
public status converttoentityattribute(integer dbdata){
return status.of(dbdata);
}
}
使用@convert 注解
@entity
public class user{
@id
private integer userid;
private string name;
private integer age;
@convert(converter = statusconverter.class, attributename = "status")
private status status;
}
在上面的例子中使用了@convert 注解,它有两个属性,一个是 converter,用于指定转换器,另一个是 attributename,用于指定要转换的属性名,如果转换器设置了 autoapply,则可以省略这个注解。配置完之后,我们就可以在实体类中使用自定义的枚举映射了。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论