Mybatis-plus uses enumerated types to define attribute mapping databases

In business types, it often appears that the field in the database is of the char type, and then the type needs to be judged and returned to the front end.
For example, the database 0 indicates that the gender is male, 1 indicates that the gender is female, and then the Entity entity class is mapped through Integer, and then returned to the front end. It is usually necessary to judge before returning. This is not only bloated, but also not conducive to maintenance, so we can use the enumeration function provided by Mybatis-Plus to solve this scenario

1: Create an enumerated type

public enum UserSexEnum {
    
    
    Male("男","m"),
    Female("女","f"),
    Other("其他","n");


    private UserSexEnum(String name,String value){
    
    
        this.name = name;
        this.value = value;
    }


    private String name;
    @EnumValue//MP提供的枚举表示插入数据库时插入该值
    private String value;


    @Override
    public String toString(){
    
    
        System.out.println("调用 toString");
        return this.name;
    }

    @JsonValue //get方法上加上此注解表示对枚举序列化时返回此字段
    public String getName() {
    
    
        return name;
    }

    public String getValue() {
    
    
        return value;
    }

}

2 Use the annotation in the entity class

@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
@TableName("user")
public class User  {
    
    

    @TableId(type = IdType.AUTO)
    private Long id;
    private String name;
    private Integer age;
    private Date birthday;
    private String cmd;
    private UserSexEnum sex =UserSexEnum.Other; //使用枚举
}

3 Use:
When adding, the sex from the front end should be Male, Female or Other, and then mybatis-plus will get the value of the corresponding enumeration and insert it into the database.
When querying data, mybatis-plus will also map the type of the database to an enumeration, and then use Jackson to return male, female or other

Guess you like

Origin blog.csdn.net/dndndnnffj/article/details/109842130