Comprehensive Guide to MyBatis‑Plus CRUD, Configuration, and Advanced Features in Spring Boot
This article provides a step‑by‑step tutorial on using MyBatis‑Plus with Spring Boot, covering database creation, table definition, Maven dependencies, entity and mapper setup, CRUD operations, automatic field filling, optimistic locking, pagination, logical deletion, performance monitoring, query wrappers, and code generation, all illustrated with complete code examples.
This guide starts by creating a MySQL database named mybatis_plus and a user table with fields id, name, age, and email. The table definition includes primary key and comments for each column.
DROP TABLE IF EXISTS user;
CREATE TABLE user (
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');Next, a Spring Boot project is initialized and the following Maven dependencies are added: MySQL driver, Lombok, and mybatis-plus-boot-starter (version 3.0.5). It is recommended not to import both MyBatis and MyBatis‑Plus to avoid version conflicts.
<!-- Database driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- MyBatis‑Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>The application.yml file configures the datasource, driver class, username, and password, and enables MyBatis‑Plus logging:
spring:
profiles:
active: dev
datasource:
url: jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImplThe entity class User is annotated with Lombok's @Data, @AllArgsConstructor, and @NoArgsConstructor, and defines fields matching the table columns.
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}A mapper interface extends BaseMapper<User>, providing all CRUD methods out of the box.
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kwhua.pojo.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper extends BaseMapper<User> { }Typical CRUD tests are shown: inserting a user (auto‑generating the primary key), updating by ID, selecting by ID, batch selection, and deleting (both physical and logical). The article also demonstrates automatic field filling for gmt_create and gmt_modified using @TableField(fill = FieldFill.INSERT) and a custom MetaObjectHandler implementation.
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("gmt_create", new Date(), metaObject);
this.setFieldValByName("gmt_modified", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("gmt_modified", new Date(), metaObject);
}
}Optimistic locking is enabled by adding a version field annotated with @Version and registering OptimisticLockerInterceptor as a bean. The article shows both successful and failed lock scenarios.
@Version
private Integer version;
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}Pagination is performed with MyBatis‑Plus's Page<User> object, and a pagination interceptor bean is configured.
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
Page<User> page = new Page<>(2, 5);
userMapper.selectPage(page, null);Logical deletion is achieved by adding a deleted column, annotating it with @TableLogic, and configuring a LogicSqlInjector bean together with global config values for deleted and not‑deleted states.
@TableLogic
private Integer deleted;
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}A performance interceptor limits SQL execution time (e.g., 100 ms) and formats the output.
@Bean
@Profile({"dev", "test"})
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor pi = new PerformanceInterceptor();
pi.setMaxTime(100);
pi.setFormat(true);
return pi;
}The article also covers the use of QueryWrapper for building dynamic queries (e.g., .isNotNull(...).ge(...)) and simple equality checks.
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.isNotNull("name").isNotNull("email").ge("age", 18);
List<User> users = userMapper.selectList(wrapper);Finally, a code generator example demonstrates how to configure AutoGenerator to produce entity, mapper, service, and controller classes automatically based on database tables.
AutoGenerator mpg = new AutoGenerator();
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("kwhua");
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/kwhua_test?useSSL=false&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
PackageConfig pc = new PackageConfig();
pc.setParent("com.kwhua");
pc.setModuleName("model");
mpg.setPackageInfo(pc);
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("user", "course");
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
mpg.setStrategy(strategy);
mpg.execute();Overall, the article serves as a practical reference for developers integrating MyBatis‑Plus into Spring Boot projects, covering essential configurations, common pitfalls, and advanced features.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
