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
@TableId
First, use annotations to annotate the primary key field in the entity class , and set type
it IdType.AUTO
to 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 BaseMapper
and 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 AUTO
indicate 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 @TableId
to 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 BaseMapper
and 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.