In those years, we learned the common notes of mybatis plus (12)

Posted by eyaly on Sun, 06 Mar 2022 22:22:30 +0100

  • 👏 About the author: Hello, I'm cabbage ~ ~, a sophomore in school, and a new star creator in the Java field.
  • 📝 Personal homepage: Cabbage CSDN blog
  • 📧 If there are mistakes in the knowledge points of the article, please correct them! Learn and make progress with you 👀
  • 🔥 If you feel the blogger's article is good, please 👍 Three company support 👍 Check out the blogger

1, Foreword

I recently learned mybatis plus. Now let's review what annotations we often use and what functions these annotations have in the process of learning? How do I use these annotations? Especially suitable for novice learning and veteran review~

No more nonsense, let's start quickly!

2, Introduction to mybatis plus

MyBatis plus (MP for short) is an enhancement tool of MyBatis. On the basis of MyBatis, it only makes enhancement without change, and is born to simplify development and improve efficiency.

The vision is to be MyBatis's best partner!

Official address: https://baomidou.com/

Document publishing address: https://baomidou.com/pages/24112f

3, Common notes (12)

1,@MapperScan

@SpringBootApplication
@MapperScan("com.cabbage.mapper")
public class Mybatisplus01Application {
    public static void main(String[] args) {
        SpringApplication.run(Mybatisplus01Application.class, args);
    }
}


Combined with the code and pictures, the partners can guess that the annotation @ MapperScan is used to scan the mapping file of mapper. Only after using it can we use various methods provided by the official.

2,@Mapper

@Mapper
@Repository
public interface UserMapper extends BaseMapper<User> {
    /**
     * Query the set according to the map id
     * @param id
     * @return
     */
    Map<String,Object> selectMapById(Long id);
}

Why do I introduce this annotation in the second one? This is because @ Mapper does not need to write annotation @ MapperScan again after acting on entity classes in the database. The difference between them is that @ Mapper can only map one entity class, while @ MapperScan can map entity classes under the whole package, which has a wider range and easier operation.

3,@TableName

First look at the following code:

@Data
//Set the table name corresponding to the entity class
@TableName("t_user")
public class User {
    @TableId(value = "id",type = IdType.AUTO)
    private Long uid;

    @TableField(value = "name")
    private String name;

    private Integer age;
    private String email;

    @TableField(value = "is_deleted")
    @TableLogic
    private Integer isDeleted;
}

As we all know, when the class name of the entity class type is inconsistent with the table name of the table to be operated, an error will be reported, and the annotation @ TableName can help us solve this problem. My database table name is t_ User. The entity class name is user. Just write @ TableName("t_user") on the class name

4,@Data

This annotation also greatly simplifies our development. Why do you say so? It's because using this annotation, you can omit getter(), setter(), toString(), and rewrite the equals() and hashCode() methods of this class. Isn't it surprising to hear that?

5,@TableId

When mybatis plus implements addition, deletion, modification and query, it will take id as the primary key column by default, and when inserting data, it will default
The policy generation id based on the snowflake algorithm is unknown here.

When the @ TableId(value = "id") statement is used, if the primary key in the entity class and table is not id, but other fields, such as uid in the code, mybatis plus will automatically identify uid as the main key column, otherwise such an error will be reported:

When using @ TableId(value = "id",type = IdType.AUTO) statement, it means that the self increment strategy of the database is used. Note that for this type, please ensure that the database is set with id self increment, otherwise it is invalid!

Of course, the function of @ TableId can also be written in application In the YML configuration file, the configuration is as follows:

mybatis-plus:
  global-config:
    banner: false
    db-config:
      # Configure the default prefix of mybatis plus operation table
      table-prefix: "t_"
      # Configure the primary key policy of mybatis plus
      id-type: auto
  # Configure MyBatis log
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

6,@TableField

When mybatis plus executes an SQL statement, it is necessary to ensure that the attribute name in the entity class is consistent with the field name in the table, otherwise an error will be reported. The statement @ TableField(value = "is_deleted") means to make the is in the database table_ Deleted is the same as the isDeleted field name in the entity class.

be careful:

  • If the attribute in the entity class uses hump naming style and the field in the table uses underline naming style
    For example, the entity class attribute userName and the field user in the table_ Name, at this time, mybatis plus will automatically convert the underline naming style into hump naming style
  • If the attributes in the entity class and the fields in the table do not meet the above conditions, such as the entity class attribute name and the field username in the table, you need to use @ TableField("username") on the entity class attribute to set the field name corresponding to the attribute

7,@TableLogic

Before we talk about this annotation, let's first understand logical deletion.

  • Physical delete: real delete, delete the corresponding data from the database, and then query the deleted data
  • Logical deletion: false deletion, which changes the status of the field representing whether to be deleted in the corresponding data to "deleted status". After that, this data record can still be seen in the database
  • Usage scenario: data recovery can be performed

    In my database table, is_ When delete is 1, it represents a logical deletion, is_ When delete is 0, it means that it has not been deleted

The use of annotation @ TableLogic means that the attributes in this class are logically deleted attributes

be careful:

  • When testing logical deletion, the real implementation is to modify UPDATE t_user SET is_deleted=1 WHERE id=? AND is_deleted=0
  • Test the query function. The logically deleted data will not be queried by default. Select id, username, as name, age, email, is_ deleted FROM t_ user WHERE is_ deleted=0

When learning the mybatis plus paging plug-in, we need to configure the interceptor. Look at the code:

@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = 
                new MybatisPlusInterceptor();
        
        interceptor.addInnerInterceptor
                (new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

8,@Configuration

I believe you have seen this annotation many times and may be a little impatient, but I still want to mention here that the class using this annotation represents a configuration class and the class itself is also a Bean. You can also load beans in this class and use @ Bean annotation

9,@Bean

Annotation @ Bean means to inject the objects in the method into the spring container, which is convenient to take out the objects in the container later to simplify development. It is often used together with @ Configuration annotation. I believe you often see this annotation. I won't talk about it here~

Now that we have talked about paging plug-ins, let's take a simple look at their basic usage

    @Test
    void test01() {
        //Set paging parameters
        Page<User> page = new Page<>(1, 3);
        userMapper.selectPage(page, null);
        //Get paging data
        List<User > list = page.getRecords();
        list.forEach(System.out::println);
        System.out.println("Current page:" + page.getCurrent());
        System.out.println("Number of items displayed per page:" + page.getSize());
        System.out.println("Total records:" + page.getTotal());
        System.out.println("Total pages:" + page.getPages());
        System.out.println("Is there a previous page:" + page.hasPrevious());
        System.out.println("Is there a next page:" + page.hasNext());
    }

Operation results:

10,@Param

When I use custom paging statements:

@Mapper
@Repository
public interface UserMapper extends BaseMapper<User> {
    /**
     * Query user information by age and paginate
     * @param page
     * @param age
     * @return
     */
    Page<User> selectPageByAge( Page<User> page, @Param("age") Integer age);
}
<mapper namespace="cabbage.mapper.UserMapper">
    <select id="selectPageByAge" resultType="User">
        SELECT id,`name`,age,email FROM `user` where age > #{age}
    </select>
</mapper>

@Param is provided by MyBatis. As the annotation of Dao layer, it is used to pass parameters, so it can correspond to the field name in SQL, which simplifies the development~

11,@Version

When we learn optimistic lock, we must have seen the following code:

@Data
@TableName("t_product")
public class Product {
    private Long id;
    private String name;
    private Integer price;
    @Version
    private Integer version;
}
@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor =
                new MybatisPlusInterceptor();
        //Paging plug-in
        interceptor.addInnerInterceptor
                (new PaginationInnerInterceptor(DbType.MYSQL));
        //Optimistic lock plug-in
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}

This annotation @ version is an important annotation to realize optimistic locking. When you want to update the data in the database, such as the price, the version will be increased by 1. If the version in the where statement is wrong, the update fails.

12,@EnumValue

@Getter
public enum SexEnum {
    MALE(1, "male"),
    FEMALE(2, "female");
    @EnumValue
    private Integer sex;
    private String sexName;

    SexEnum(Integer sex, String sexName) {
        this.sex = sex;
        this.sexName = sexName;
    }
}
mybatis-plus:
  global-config:
    banner: false
    db-config:
      # Configure the default prefix of mybatis plus operation table
      table-prefix: "t_"
      # Configure the primary key policy of mybatis plus
      id-type: auto
  # Configure MyBatis log
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#  Configure the package corresponding to the type alias
  type-aliases-package: cabbage.pojo
  # Configure scan generic enumeration
  type-enums-package: cabbage.pojo

The attribute value identified by the annotation @ EnumValue will be stored in the database, which is equivalent to the statement INSERT INTO t_user ( username, age, sex ) VALUES ( ?, ?, ? )
Parameters: Enum(String), 20(Integer), 1(Integer)

4, Summary

Well, dear friends, the common annotations of mybatis plus are almost explained. I believe you have felt the convenience and support of the domestic framework. I hope you can actively support it. If you feel the blogger's writing is good, you can give the blogger three consecutive support~~

Topics: Java Spring Back-end