Loading... # MyBatis Plus 通用枚举配置 **相信后端的同学都经历过一个情况,比如**`性别`这个字段,分别值和名称对应`1男`、`2女`,这个字段在数据库时是数值类型,而前端展示则是展示字符串的名称。有几种常见实现方案? * **数据库查询 sql 通过 case 判断,返回名称,以前 oracle 经常这么做** * **数据库返回的值,重新遍历赋值进去,这时候还需要判断这个值到底是男是女。** * **前端写死,返回 1 就是男,返回 2 就是女。** **相信无论哪种方法都有其缺点,所以我们可以使用 mybatis-plus 提供的方式。我们在返回给前端时:** * **只需要在遍历时 get 这个枚举,直接赋值其名称,不需要再次判断。** * **直接返回给前端,让前端去去枚举的 name** **这样大家都不需要写死这个值。** **下面看看如何实现这个功能:** ## 定义枚举,实现 IEnum 接口: ``` import com.baomidou.mybatisplus.annotation.IEnum; import com.fasterxml.jackson.annotation.JsonFormat; /** * @description: 性别枚举 * @author:dpl * @date:2022/1/17 16:26 * @version:3.0 */ @JsonFormat(shape = JsonFormat.Shape.OBJECT) public enum SexEnum implements IEnum<Integer> { MAN(1, \"男\"), WOMAN(2, \"女\"); private Integer code; private String name; SexEnum(Integer code, String name) { this.code = code; this.name = name; } @Override public Integer getValue() { return code; } public String getName() { return name; } } ``` **@JsonFormat 注解为了解决枚举类返回前端只展示构造器名称的问题。** ## 实体类性别字段 ``` @TableName(value = \"user\") public class UserDO { /** * 主键 */ @TableId(value = \"id\", type = IdType.AUTO) private Long id; /** * 昵称 */ @TableField(value = \"nickname\",condition = SqlCondition.EQUAL) private String nickname; /** * 性别 */ @TableField(value = \"sex\") private SexEnum sex; /** * 版本 */ @TableField(value = \"version\",update = \"%s+1\") private Integer version; /** * 时间字段,自动添加 */ @TableField(value = \"create_time\",fill = FieldFill.INSERT) private LocalDateTime createTime; } ``` ## 配置文件扫描枚举 ``` mybatis-plus: # 支持统配符 * 或者 ; 分割 typeEnumsPackage: com.wjbgn.*.enums ``` ### 定义配置文件 ``` @Bean public MybatisPlusPropertiesCustomizer mybatisPlusPropertiesCustomizer() { return properties -> { GlobalConfig globalConfig = properties.getGlobalConfig(); globalConfig.setBanner(false); MybatisConfiguration configuration = new MybatisConfiguration(); configuration.setDefaultEnumTypeHandler(MybatisEnumTypeHandler.class); properties.setConfiguration(configuration); }; } ``` ## 序列化枚举值为数据库值 **以下我是使用的 fastjson:** ### 全局(添加在前面的配置文件中): ``` @Bean public MybatisPlusPropertiesCustomizer mybatisPlusPropertiesCustomizer() { // 序列化枚举值为数据库存储值 FastJsonConfig config = new FastJsonConfig(); config.setSerializerFeatures(SerializerFeature.WriteEnumUsingToString); return properties -> { GlobalConfig globalConfig = properties.getGlobalConfig(); globalConfig.setBanner(false); MybatisConfiguration configuration = new MybatisConfiguration(); configuration.setDefaultEnumTypeHandler(MybatisEnumTypeHandler.class); properties.setConfiguration(configuration); }; } ``` ## 局部 ``` @JSONField(serialzeFeatures= SerializerFeature.WriteEnumUsingToString) private SexEnum sex; ``` 最后修改:2023 年 03 月 03 日 © 允许规范转载 赞 如果觉得我的文章对你有用,请点个赞吧~