前言

在实际开发中,对于一些状态类的字段,我们通常使用的是枚举,而保存到数据库时,我们是用的枚举的某一个属性进行保存的,这里就会有一个问题,在PO类中,如果我们直接使用枚举类型去映射数据库的对应字段保存时,往往就会因为类型不匹配导致映射失败,如果要解决这个问题,办法有很多种,Mybatis-plus提供了一种解决办法,就是使用@EnumValue注解,这里我们就使用这种方式。

Maven引入的依赖

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.0</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

Demo

PO类
@Data
@TableName(value = "urge_reduce_rule")
public class ReduceRule {
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    @TableField(value = "charge_category")
    private ChargeCategoryEnum chargeCategoryEnum;

    @TableField(value = "name")
    private String name;
}
枚举类(@EnumValue注解就用在这里)
@Getter
public enum ChargeCategoryEnum {

    CHARGE("CHARGE",1,"基本费"),
    PENALTY("PENALTY",2,"违约金");

    private String code;
    
    @EnumValue  //在需要保存到数据库的值上面加上注解
    private Integer value;
    
    private String text;

    public String getCode() {
        return code;
    }

    ChargeCategoryEnum(String code, Integer value, String text) {
        this.code = code;
        this.value = value;
        this.text = text;
    }
}
mapper类
@Mapper
public interface ReduceRuleMapper extends BaseMapper<ReduceRule> {
}
配置文件
#配置枚举 支持通配符 * 或者 ; 分割。指定枚举类所在的包
mybatis-plus:
  type-enums-package: com.demo.mybatisplus.enum 
  configuration:
    default-enum-type-handler: org.apache.ibatis.type.EnumOrdinalTypeHandler
  #handler配置可以省略不写,默认配置就是上面这个Handler
测试代码
@SpringBootTest(classes = DemoApplication.class)
class DemoApplicationTests {
    @Resource
    private ReduceRuleMapper reduceRuleMapper;

    @Test
    void test1(){
        ReduceRule reduceRule = new ReduceRule();
        reduceRule.setName("名字");
        reduceRule.setChargeCategoryEnum(ChargeCategoryEnum.PENALTY);
        reduceRuleMapper.insert(reduceRule);
    }
    
    @Test
    void test2(){
        ReduceRule reduceRule = reduceRuleMapper.selectById(32L);
        System.out.println(reduceRule);
    }
}

拓展

如果返回给前端不希望直接将枚举返回的话,需要在枚举类上加上 @JsonValue 注解

@Getter
public enum ChargeCategoryEnum {

    CHARGE("CHARGE",1,"基本费"),
    PENALTY("PENALTY",2,"违约金");

    private String code;
    
    @EnumValue  //在需要保存到数据库的值上面加上注解
    private Integer value;
    
    @JsonValue    //需要在前端展示哪个值就在哪个属性上加上该注解
    private String text;

    public String getCode() {
        return code;
    }

    ChargeCategoryEnum(String code, Integer value, String text) {
        this.code = code;
        this.value = value;
        this.text = text;
    }
}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐