mybatis plus 枚举类型
添加mybatis-plus依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis.plus.version}</version>
</dependency>
配置枚举扫描
mybatis-plus:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.demo.entity.po
type-enums-package: com.demo.contants.enum
数据库表结构
create table base_user
(
user_id bigint unsigned auto_increment comment '主键id'
primary key,
username varchar(30) null comment '用户名',
phone varchar(20) null comment '手机号',
password varchar(128) null comment '密码',
salt varchar(32) not null comment '加盐',
type tinyint(1) default 1 null comment '用户类型:1用户/2员工/3供应商',
is_deleted tinyint(1) default 0 not null comment '是否删除(0:否;1是)',
created_at datetime null comment '创建时间',
updated_at datetime null comment '更新时间',
deleted_at datetime null comment '删除时间'
)
comment '基础数据-用户表';
对应实体类
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("base_user")
@ApiModel(value = "User对象", description = "基础数据-用户表")
public class User extends Model<User> {
private static final long serialVersionUID = 1L;
@TableId(value = "user_id", type = IdType.AUTO)
private Long userId;
private String username;
private String phone;
private String password;
private String salt;
private UserTypeEnum type;
@TableField(value = "created_at")
private LocalDateTime createdAt;
@TableField(value = "updated_at", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updatedAt;
private LocalDateTime deletedAt;
@TableField("is_deleted")
@TableLogic
private Boolean deleted;
@Override
protected Serializable pkVal() {
return this.userId;
}
}
枚举类
import com.baomidou.mybatisplus.annotation.EnumValue;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Arrays;
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum UserTypeEnum {
USER(1, "用户"),
STAFF(2, "员工"),
SUPPLIER(3, "供应商");
@EnumValue
private int code;
private String name;
UserTypeEnum(int code, String name) {
this.code = code;
this.name = name;
}
@JsonCreator
public static UserTypeEnum getByCode(@JsonProperty("code") int code) {
return Arrays.stream(UserTypeEnum.values()).filter(item -> item.code == code).findFirst().get();
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}