中文 English

[Transfer] The use of Mybatis-Plus general enumeration types

Published: 2022-02-02

Some fields, such as gender, marital status, and other iconic fields, are often stored in the database in the form of numbers, 0 or 1. The advantage of this is that it has high access efficiency and saves space. However, the front-end cannot be displayed directly during display. A judgment is required, but it is inappropriate to place the judgment logic on the front-end, so the back-end should convert the value in advance and return it to the front-end.

In Mybatis-Plus we can use 枚举类型 to complete this operation. It can automatically map the fields in the database to the fields we need, such as gender. The new enumeration class is as follows: The most critical one is the @EnumValue annotation, which annotates the fields stored in the database. Here, the database stores key, and @JsonValue annotates the fields to be displayed. Here we want to display the name field to the front end, and at the same time rewrite toString The method is what we want, because the system will automatically call this method as the front-end display value. Here we want to display name, so just return it directly.

Key points:

At the same time, we need to modify the type in the entity class associated with the database and change the gender field to an enumeration type: Configure the scanning annotation type in the configuration file:

#mybatis-plus configuration If you query again at this time, the returned result will be directly the name value we defined in the enumeration type.

Original link: https://blog.csdn.net/weixin_43941364/article/details/119821877

@Getter
public enum GenderType {
    WOMEN(0, "女"),
    MAN(1, "男");

    @EnumValue
    private Integer key;

    @JsonValue
    private String name;

    GenderType(Integer key, String name) {
        this.key = key;
        this.name = name;
    }
    
    @Override
    public String toString() {
        return this.name;
    }
}
@Data
@TableName("table")
public class ZhbfDb extends SymqBaseEntity {
    /**
     * 姓名
     */
    private String name;
    /**
     * 性别
     */
    private GenderType gender;
}
mybatis-plus:
  type-enums-package: com.demo.test.enums