1. 使用mybatis-plus转换枚举值
枚举值转换方式有很多,有以下方式:
- 后端写一个通用方法,只要前端传枚举类型,后端返回相应的枚举值前端去匹配
优点:能够实时保持数据一致性
缺点:如果有大量的枚举值转换,请求频繁,对服务造成不必要的压力,可以优化:将每个页面配置一个大的枚举,然后里边包含具体的枚举,这样操作比较繁琐,新增枚举都要修改,不推荐使用 - 使用注解
以下介绍以下使用mybatis-plus的注解处理枚举值,当然也可以自定义注解完成枚举值的转换
1.1 方式一
实现IEnum方法
public enum SexEnum implements IEnum<Integer> {
MALE(1, "男"),
FEMALE(2, "女");
SexEnum(Integer code, String value) {
this.code = code;
this.value = value;
}
private final Integer code;
private final String value;
@Override
public Integer getValue() {
return this.code;
}
}
===================================vo=========================
public class UserVo {
private Long id;
private String name;
private Integer age;
private String email;
/**
* VO性别类型为刚刚新建的枚举类型
*/
private SexEnum sex;
}
yml中的配置:
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
type-enums-package: com.example.mybatisplus.enum #枚举类的包路径,一定不也能错,否则报错
1.2 方式二
public enum SexEnum {
MALE(1, "男"),
FEMALE(2, "女");
SexEnum(Integer code, String value) {
this.code = code;
this.value = value;
}
/**
* 标记数据库存的值是code
*/
@EnumValue
private final Integer code;
/**
* 要返回的值
*/
private final String value;
public Integer getCode() {
return code;
}
public String getValue() {
return value;
}
}
其余的都一样