Master MyBatis-Plus in Spring Boot: From Setup to Advanced Features
This tutorial walks you through integrating MyBatis-Plus with Spring Boot, covering environment preparation, Maven dependencies, configuration of data sources, entity annotations, CRUD operations, pagination, logical deletion, enum handling, automatic field filling, multi‑datasource support, and testing with a REST controller.
Quick Start
Prepare a Spring Boot, Maven, JDK 1.8, and MySQL environment; optionally use Nacos as a service registry.
Dependency Setup
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.0</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency> <dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>Configuration
Configure the main class with @MapperScan and @EnableDiscoveryClient.
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@MapperScan("com.wjbgn.user.mapper")
@SpringBootApplication
public class RobNecessitiesUserApplication {
public static void main(String[] args) {
SpringApplication.run(RobNecessitiesUserApplication.class, args);
}
}Define datasource properties for master and slave (utf8mb4 charset is recommended).
spring:
datasource:
dynamic:
primary: master
strict: false
datasource:
master:
url: jdbc:mysql://127.0.0.1:3306/rob_necessities?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: 123456
slave_1:
url: jdbc:mysql://127.0.0.1:3306/rob_necessities?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: 123456Adjust HikariCP settings for connection pool stability.
spring:
datasource:
dynamic:
hikari:
max-lifetime: 1800000
connection-timeout: 5000
idle-timeout: 3600000
max-pool-size: 12
min-idle: 4
connection-test-query: /**ping*/Usage
Entity Annotations
Use @TableName, @TableId, and @TableField to map Java classes to database tables.
@TableName("user")
public class UserDO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("nickname")
private String nickname;
private String realName;
}@TableName specifies the table name.
@TableId defines the primary key and its generation strategy.
@TableField customizes column name and query condition.
CRUD Operations
Service layer extends IService; implementation extends ServiceImpl.
public interface IUserService extends IService<UserDO> {}
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements IUserService {}Mapper extends BaseMapper.
@Mapper
public interface UserMapper extends BaseMapper<UserDO> {}Pagination
Configure MybatisPlusInterceptor with PaginationInnerInterceptor.
@Configuration
@MapperScan("com.wjbgn.*.mapper*")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}Logical Delete
Set global logical‑delete configuration or annotate a field with @TableLogic.
mybatis-plus:
global-config:
db-config:
logic-delete-field: isDelete
logic-delete-value: 1
logic-not-delete-value: 0 @TableLogic
private Integer isDelete;Enum Mapping
Implement IEnum and use @JsonFormat to serialize enum values.
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum SexEnum implements IEnum<Integer> {
MAN(1, "男"),
WOMAN(2, "女");
private Integer code;
private String name;
@Override
public Integer getValue() { return code; }
public String getName() { return name; }
}Configure the package for enum scanning and set the default enum type handler.
mybatis-plus:
typeEnumsPackage: com.wjbgn.*.enums @Bean
public MybatisPlusPropertiesCustomizer mybatisPlusPropertiesCustomizer() {
return properties -> {
GlobalConfig globalConfig = properties.getGlobalConfig();
globalConfig.setBanner(false);
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setDefaultEnumTypeHandler(MybatisEnumTypeHandler.class);
properties.setConfiguration(configuration);
};
}Auto Fill
Use FieldFill in @TableField and implement MetaObjectHandler to populate timestamps.
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
}
@Override
public void updateFill(MetaObject metaObject) {
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
}
}Multi‑Datasource
Define multiple master/slave or different database types in the dynamic datasource configuration.
spring:
datasource:
dynamic:
primary: master
datasource:
master_1: ...
slave_1: ...
# additional datasourcesTesting
Create the user table, implement a REST controller for CRUD and pagination, and verify the endpoints.
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
@PostMapping("/save")
public boolean save() {
UserDO user = new UserDO();
user.setNickname("大漂亮");
user.setSex(SexEnum.MAN);
return userService.save(user);
}
// other endpoints for update, delete, list, page ...
}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.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.
