数据库中枚举类型的数据如何映射java bean中的枚举字段


问题描述:数据库中的 性别字段 sex 存放的数据为 1或2 响应数据时需要转化成页面展示的文本

方式1:使用mytais-plus中的配置

1、环境

springboot
mybatis-plus

2 、代码实现

2.1定义枚举常量

public enum SexEnum {
    man(1, "男"),
    woman(2, "女"),
    ;
    
    @EnumValue  //表示插入进数据库的值
    private Integer type;
    
    @JsonValue  // 不加 @JsonValue 注解,查询接口的sex字段显示的是 man/woman
    private String name;

    SexEnum(Integer type, String name) {
        this.type = type;
        this.name = name;
    }

    public Integer getType() {
        return type;
    }

    public String getName() {
        return name;
    }
}

2.2 添加配置

mybatis-plus:
  #配置与数据库对应的枚举包
  typeEnumsPackage: com.wyp.mybatisplusdemo.module01.constants.enums
  configuration:
    default-enum-type-handler: org.apache.ibatis.type.EnumOrdinalTypeHandler

方式2:其他方式

参考:
SpringBoot 使用枚举

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐