Master MyBatis-Plus in Spring Boot: Setup, Config, and Advanced Usage
A comprehensive guide walks you through integrating MyBatis-Plus with Spring Boot, detailing dependency setup, configuration, entity annotations, CRUD operations, pagination, logical deletion, enum mapping, automatic field filling, multi‑datasource handling, and testing, all illustrated with runnable code examples.
This article introduces the MyBatis-Plus plugin for Spring Boot users, covering dependency inclusion, configuration, usage, and advanced features such as pagination, logical deletion, enum handling, automatic field filling, and multi‑datasource support.
1. Quick Start
The project uses Spring Boot, Maven, JDK 1.8, and MySQL. Prepare the environment and optionally use Nacos as a service registry.
Create the database (UTF8MB4 charset is recommended for storing emoji characters).
1.1 Dependency Preparation
Add the following Maven dependencies:
<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>
<!-- mybatis-plus multi‑datasource -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>1.2 Configuration Preparation
Configure the Spring Boot main class to scan mapper interfaces:
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);
}
}Configure the datasource (example shows a master‑slave setup using HikariCP):
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: 123456
hikari:
max-lifetime: 1800000
connection-timeout: 5000
idle-timeout: 3600000
max-pool-size: 12
min-idle: 4
connection-test-query: /**ping*/1.3 Start Service
Run the Spring Boot application; a successful start prints a log similar to the screenshot below.
2. Usage
2.1 Entity Annotations
MyBatis‑Plus provides convenient annotations. Example entity:
@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 – marks the primary key and its generation strategy. @TableField – maps a field to a column.
Key IdType values:
Name
Description
AUTO
Database auto‑increment ID
NONE
Unspecified (follows global config)
INPUT
User‑provided ID
ASSIGN_ID
Snowflake algorithm generated ID when value is null
ASSIGN_UUID
UUID generated ID when value is null
2.2 CRUD
Service layer extends IService and implementation extends ServiceImpl:
import com.baomidou.mybatisplus.extension.service.IService;
public interface IUserService extends IService<UserDO> {}
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements IUserService {}Mapper layer extends BaseMapper:
@Mapper
public interface UserMapper extends BaseMapper<UserDO> {}2.3 Pagination
Add the pagination interceptor:
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.wjbgn.*.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}2.4 Logical Deletion
Global configuration:
mybatis-plus:
global-config:
db-config:
logic-delete-field: isDelete
logic-delete-value: 1
logic-not-delete-value: 0Or annotate the field:
@TableLogic
private Integer isDelete;2.5 Enum Mapping
Define an enum implementing IEnum and annotate with @JsonFormat to return name/value to the front end:
import com.baomidou.mybatisplus.annotation.IEnum;
import com.fasterxml.jackson.annotation.JsonFormat;
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum SexEnum implements IEnum<Integer> {
MAN(1, "男"),
WOMAN(2, "女");
private Integer code;
private String name;
SexEnum(Integer code, String name) { this.code = code; this.name = name; }
@Override
public Integer getValue() { return code; }
public String getName() { return name; }
}Use the enum in the entity:
@TableField("sex")
private SexEnum sex;Configure package scanning for enums:
mybatis-plus:
typeEnumsPackage: com.wjbgn.*.enums2.6 Automatic Field Filling
Implement MetaObjectHandler:
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@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());
}
}Entity fields:
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;2.7 Multi‑Datasource
Supported configurations include master‑slave, multiple masters, and mixed database types. Example master‑slave YAML shown above. Use @DS("slave_1") on classes or methods to switch datasource.
@DS("slave_1")
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements IUserService {
@DS("slave_1")
public List<UserDO> getList() { return this.list(); }
@DS("master")
public int saveUser(UserDO user) { return this.save(user) ? 1 : 0; }
}3. Testing
Create the user table (UTF8MB4 charset) and a simple controller to verify CRUD, pagination, and logical delete operations.
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nickname` varchar(255) NOT NULL COMMENT '昵称',
`sex` tinyint(1) NOT NULL COMMENT '性别,1男2女',
`create_time` datetime NOT NULL COMMENT '创建时间',
`is_delete` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否删除 1是,0否',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;Controller example:
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
@RequestMapping("/save")
public boolean save() {
UserDO user = new UserDO();
user.setNickname("大漂亮");
user.setSex(SexEnum.MAN);
return userService.save(user);
}
@RequestMapping("/update")
public boolean update(@RequestParam String nickname, @RequestParam Long id) {
UserDO user = new UserDO();
user.setNickname(nickname);
user.setId(id);
return userService.updateById(user);
}
@RequestMapping("/delete")
public boolean delete(@RequestParam Long id) {
return userService.removeById(id);
}
@RequestMapping("/list")
public List<UserDO> list() { return userService.list(); }
@RequestMapping("/page")
public Page<UserDO> page(@RequestParam int current, @RequestParam int size) {
return userService.page(new Page<>(current, size), new QueryWrapper<>(new UserDO()));
}
}Running these endpoints confirms that MyBatis‑Plus is correctly integrated and all features work as expected.
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.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
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.
