定义表
num字段在java的实体类中定义为枚举
枚举类
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Getter;
import java.util.Arrays;
/**
* Created with IntelliJ IDEA.
*
* @auther: lkz
* @date: 2021/04/03
* @version: 1.0
* @description:
*/
@Getter
// 让枚举返回的时候携带里面的值
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum NumEnum {
M_0(0, "0的枚举"),
M_1(1, "1的枚举"),
M_2(2, "2的枚举"),
UNKNOWN(-1, "未知");
private Integer code;
private String msg;
private NumEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
// 自定义反序列函数
// JsonCreator.Mode.DELEGATING: 接收单个值,将接收的值整个传入自定义函数
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static NumEnum get(Integer code) {
if (code == null) return UNKNOWN;
return Arrays.stream(NumEnum.values()).filter(i -> i.getCode() == code.intValue()).findAny().orElse(UNKNOWN);
}
}
实体类
@Data
@Entity
@Table(name = "jpaenum")
public class Test implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = IDENTITY)
private int id;
@Column(name = "num")
// 关键 自定义转化器
@Convert(converter = TestConverter.class)
private NumEnum num;
}
转换器
public class TestConverter implements AttributeConverter<NumEnum, Integer> {
@Override
public Integer convertToDatabaseColumn(NumEnum attribute) {
if (attribute == null) return -1;
return attribute.getCode();
}
@Override
public NumEnum convertToEntityAttribute(Integer dbData) {
return NumEnum.get(dbData);
}
}
完成