Commonly used annotations in Mybatis-plus

1. Annotation display

        MyBatis-Plus  (MP for short) is an  enhancement tool for MyBatis  . Based on MyBatis, it only enhances without making any changes. It is created to simplify development and improve efficiency. Annotations expand the development functions and ensure the flexibility of the code, so MP's annotations make the code more streamlined and flexible. The following is an introduction to some MP annotations:

        1. @TableName: used to identify the mapping relationship between entity classes and database tables. It can be used on entity classes to specify the corresponding database table name. 

        2. @TableId: used to identify the primary key field of the entity class. Can be used on the primary key field to specify the primary key generation strategy. 

        3. @TableField: Used to identify the mapping relationship between the fields of the entity class and the fields of the database table. It can be used on entity class fields to specify the corresponding database table field name. 

        4. @Version: Optimistic locking field used to identify entity classes. Can be used on optimistic locking fields to handle concurrent update conflicts.

        5. @EnumValue: used to identify the enumeration field of the entity class. Can be used on enumerated fields to specify the corresponding database storage value. 

        6. @TableLogic: Used to identify tombstone fields of entity classes. Can be used on a tombstone field to specify the tombstone value.  

        7. @SqlParser: Used to identify whether the fields of the entity class participate in SQL parsing. Can be used on entity class fields. 

        8. @KeySequence: used to identify the primary key sequence of entity classes. Can be used on entity classes. 

        9. @InsertFill: used to automatically fill in field values ​​when inserting data. 

        10. @UpdateFill: Used to automatically fill in field values ​​when updating data. 

        11. @SqlParser: Used to identify whether to participate in SQL parsing. 

        12. @SqlStatement: used to specify custom SQL statements. 

        13. @ResultMap: used to specify the mapping relationship of the result set, which can be used in XML configuration files. 

        14. @SelectProvider: used to specify the provider of dynamic SQL. 

        15. @UpdateProvider: used to specify the provider of dynamically updating SQL. 

        16. @DeleteProvider: used to specify the provider of dynamic deletion SQL. 

2. Practical display 

2.1.@TableName 和 @TableId

Visualization tools: 

Project examples: 

        It can be seen that the value of the @TableName annotation is the same as the table name in the visualization tool, and the @TableId annotation is placed above the field corresponding to the primary key of the table. MP will automatically identify the field as the primary key when parsing. View the source code of the two annotations

        As can be seen from the meta-annotations   , the @Inherited annotation is omitted, which means that these two annotations cannot be inherited by subclasses. Therefore, you can see that in the above project examples, the annotations are placed on subclasses.

2.2.@TableField 

        First check the source code of @TableField annotation 

         It can be seen from the source code that when the value of [database field value is converted to uppercase after removing underscores and spaces] is equal to the value of [entity attribute name is converted to uppercase], this annotation is not needed. On the contrary, in MP, when the two values ​​​​are not equal, or when the field is not included in the database, the @TableField annotation needs to be added to the entity attribute name. AI examples are as follows:

public class User {

    // 普通字段映射
    @TableId(type = IdType.AUTO)
    private Long id;          // 数据库表字段名为 "id"

    @TableField(value = "name", exist = true)
    private String username; // 数据库表字段名为 "name"

    private Integer age;     // 数据库表字段名为 "age"

    // 非数据库表字段,不参与映射
    @TableField(exist = false)
    private String password;

    // getter 和 setter 省略
}
 

2.3.@Version 

        @Version is one of the annotations provided by Spring Data JPA. Adding @Version to the entity class can achieve optimistic locking. Specific practical examples are as follows:

        First, add the @Version annotation to the entity class, as shown below:

@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String email;

    @Version
    private Long version;

    // 省略getter/setter方法
}

        Among them, the version field is the version number of optimistic locking.

        Next, you need to add version number restrictions when updating data, otherwise the update operation will fail. The sample code is as follows:

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    /**
     * 更新用户信息
     *
     * @param user 用户信息
     */
    public void updateUser(User user) {
        userRepository.save(user);
    }
}

        When executing the updateUser method, if the version number has been updated by other threads, an OptimisticLockException will be thrown to avoid data conflicts.

 2.4.@EnumValue

@EnumValue is a very practical annotation that can define a field in the enumeration class and map the field to the value of the enumeration value. For example, we can define an enumeration class Gender to represent gender:

public enum EnumMsg{
    SUCCESS(0, "交易成功"),
    FAIL(1, "交易失败"),
    ERROR(2, "交易异常");

    @EnumValue
    private final int value;

    private final String name;

    EnumGsg(int value, String name) {
        this.value = value;
        this.name = name;
    }

    public int getValue() {
        return value;
    }

    public String getName() {
        return name;
    }
}

In this example, we define an @EnumValue annotation to map the value field to the value of the enumeration value. For example, the value attribute of the SUCCESS enumeration value is 0, the value attribute of the FAIL enumeration value is 1, and the value attribute of the ERROR enumeration value is 2.

With the @EnumValue annotation, we can use the value of the enumeration value to represent the enumeration value instead of using the name of the enumeration value. For example, we can obtain the enumeration value corresponding to MALE in the following way:

int value = EnumMsg.FAIL.getValue(); // value=1

This approach avoids typo problems caused by using the names of enumeration values. At the same time, using the @EnumValue annotation can also simplify the code and avoid using complex structures such as switch statements to compare and match enumeration values.

 

Guess you like

Origin blog.csdn.net/weixin_52255395/article/details/132759841