Mybatis plus addition: analysis and implementation of common primary key strategies

Time:2022-1-19

On the basis of mybatis, mybatis plus is only enhanced without change. The purpose is toSimplify development and improve efficiency。 The six articles in this column focus on the common technical points of mybatis plus and realize the crud operation of database records in combination with springboot. For other articles, please refer to:


Author: hudie
Official account /CSDN blog: programming a butterfly
The project is open source to gitee:https://gitee.com/guo-qianliang/mybatis-plus-test
The project is open source to GitHub:https://github.com/Guoqianliang/mybatis-plus-test


Mybatis plus automatically generates an ID

AboveIntroduction to mybatis plus: querying all records in the databaseIn, the environment has been built and the query operation has been tested. Next, the add operation is tested. The specific test code is as follows:

@Test
    public void testAdd(){
        User user = new User(null,"lucy",23,"[email protected]");
        int insert = userMapper.insert(user);
        //Returns the number of affected rows
        System.out.println(insert);
    }

Mybatis plus addition: analysis and implementation of common primary key strategies

The default primary key policy is automatically generated when adding

We did not set automatic growth when creating the table, and set the ID to null when adding. But a long string of IDS appears automatically,This string of IDS is automatically generated for us by mybatis plus. It is called the primary key policy。 Next, we will explain the key policy technology of mybatis plus.

ASSIGN_ ID default policy

The annotation can be used to implement the primary key policy. The default primary key policy of mybatis plus is:ASSIGN_ID(snowflake algorithm is used at the bottom)

    @TableId(type = IdType.ASSIGN_ID)

Mybatis plus addition: analysis and implementation of common primary key strategies

In the above primary key strategy, the most commonly used isASIGN_IDandAUTO, the remaining assign_ UUID is a random value generated automatically, and input is a manually set value.

Auto auto increment strategy

If the auto auto auto increment strategy is used, you need to set the auto increment of the primary key when creating the data table. Configure the following in the entity field:

     @TableId(type = IdType.AUTO)

To affect the configuration of all entities, you can also set the global primary key policy:

#Global setting primary key generation policy
    mybatis-plus.global-config.db-config.id-type=auto

So far, the primary key policy test of mybatis plus has been completed.