Basic usage of MyBatis - primary key auto-increment

The MyBatisPlus framework can implement the primary key auto-increment function through annotations or configuration files.

1. Annotation method to achieve primary key auto-increment

@TableIdFirst, use annotations to annotate the primary key field in the entity class , and set typeit IdType.AUTOto indicate that the self-incrementing primary key of the database is used.

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;

public class User {
    
    
    @TableId(type = IdType.AUTO)
    private Long id;
    private String username;
    private String password;
    // 省略getter和setter方法
}

Then, inherit the interface in the Mapper interface BaseMapperand specify the type of the entity class.

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

public interface UserMapper extends BaseMapper<User> {
    
    
}

2. Configuration file method to achieve primary key auto-increment

First, configure the global primary key strategy in the configuration file to AUTOindicate that the auto-increment primary key of the database is used.

mybatis-plus.global-config.db-config.id-type=AUTO

Then, use annotations in the entity class @TableIdto mark the primary key field.

import com.baomidou.mybatisplus.annotation.TableId;

public class User {
    
    
    @TableId
    private Long id;
    private String username;
    private String password;
    // 省略getter和setter方法
}

Finally, also inherit the interface in the Mapper interface BaseMapperand specify the type of the entity class.

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

public interface UserMapper extends BaseMapper<User> {
    
    
}

Quote MyBatisPlus

Add the dependency of MyBatisPlus to the pom.xml file of the project.

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.x.x</version>
</dependency>

Note: Select the appropriate version number according to the actual situation.

The above is the sample code and configuration file for implementing primary key auto-increment using the MyBatisPlus framework. According to the specific situation, choose the annotation method or the configuration file method to realize the primary key auto-increment.

Guess you like

Origin blog.csdn.net/qq_41177135/article/details/131822308