一、请求参数自动转换
@Getter
public enum UserType{
BACKEND(1, "后台"),
FRONT(2, "前台"),
;
@JsonCreator
UserType(Integer val, String desc) {
this.val = val;
this.desc = desc;
}
@EnumValue
private final Integer val;
@JsonValue
private final String desc;
}
@Data
@TableName("demo")
@Accessors(chain = true)
public class Demo {
@TableId
private Integer id;
private String name;
private Integer age;
private UserType userType;
}
@Api
@RequestMapping("/demo")
@RestController
public class DemoController {
@Resource
private DemoService demoService;
@ApiOperation("根据id获取数据")
@GetMapping("/{id}")
public R<Demo> getById(@PathVariable Integer id) {
Demo demo = demoService.getById(id);
return R.ok(demo);
}
@ApiOperation("测试枚举")
@PostMapping("/testEnum")
public R<Demo> testEnum(@RequestBody Demo demo) {
return R.ok(demo);
}
}
二、MyBatisPlus枚举转换
版本依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
yml配置
mybatis-plus:
#扫描,多个package用逗号或者分号分隔
typeEnumsPackage: io.renren.modules.*.enums
使用方法
-
使用枚举
@EnumValue
@Getter public enum UserType{ BACKEND(1, "后台"), FRONT(2, "前台"), ; @JsonCreator UserType(Integer val, String desc) { this.val = val; this.desc = desc; } @EnumValue private final Integer val; @JsonValue private final String desc; }
-
实现接口
IEnum<T>
@Getter public enum UserType implements IEnum<Integer> { BACKEND(1, "后台"), FRONT(2, "前台"), ; @JsonCreator UserType(Integer val, String desc) { this.val = val; this.desc = desc; } private final Integer val; @JsonValue private final String desc; @Override public Integer getValue() { return val; } }
三、可能存在的问题
如果数据库中使用的tinyint(1)
那么在mybatis
将会映射为boolean
,使用Integer
作为枚举类的值会映射失败,一值为Null
,解决方法是使用tinyint(4)
,因为tinyint(1)
和tinyint(4)
占用的空间是一样,故没有影响。
查考文章:https://my.oschina.net/u/3773384/blog/1802992
来源:oschina
链接:https://my.oschina.net/teddyIH/blog/3185436