1 问题的引入
package com.zs.entity.enumEntity;
@Getter
public enum GenderEnum {
MALE(1, "男"),
FEMALE(2, "女");
@EnumValue
private Integer code;
private String desc;
private GenderEnum(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
}
package com.zs.entity;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
// ...
private GenderEnum gender;
public User(Long id, String name, Integer age, String email, GenderEnum gender) {
this.id = id;
this.name = name;
this.age = age;
this.email = email;
this.gender = gender;
}
}
@Test
public void test() {
User user = new User(11L, "Leftors", 25, "Leftors@qq.com", GenderEnum.MALE);
boolean res = userService.save(user);
System.out.println(res);
}
查看数据库,可以发现 mybatis-plus原生默认是以枚举的名称 Enum.name()
作为默认值。这样就要求对应数据库的字段必须是一个varchar类型,这显然不太合适。
2 问题的解决
首先我们在 application.properties 文件中配置扫描枚举类的路径:
mybatis-plus:
type-enums-package: com.zs.entity.enumEntity
直接使用@EnumValue注解标注出真正的value是什么:
package com.zs.entity.enumEntity;
@Getter
public enum GenderEnum {
MALE(1, "男"),
FEMALE(2, "女");
@EnumValue
private Integer code;
private String desc;
private GenderEnum(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
}
@Test
public void test() {
User user = new User(12L, "James Gosling", 25, "James Gosling@qq.com", GenderEnum.MALE);
boolean res = userService.save(user);
System.out.println(res);
}