Comprehensive Guide to Using MyBatis‑Plus with Spring Boot
This tutorial walks through integrating MyBatis‑Plus into a Spring Boot project, covering dependency setup, configuration of data sources, entity annotations, service and mapper layers, pagination, logical deletion, enum handling, automatic field filling, multi‑datasource support, and testing with full code examples.
This article introduces MyBatis‑Plus, a powerful ORM plugin for Spring Boot users, and provides a complete walkthrough from project preparation to advanced features.
1. Quick Start
Prepare the environment (Spring Boot, Maven, JDK 1.8, MySQL) and optionally Nacos for service discovery.
Add the required 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>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>Configure the Spring Boot 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 the data source configuration (master‑slave example) in application.yml :
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: 123456Optionally tune HikariCP settings for better performance.
2. Usage
2.1 Entity Annotations
MyBatis‑Plus provides annotations such as @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;
}The @TableId type attribute supports values like AUTO , NONE , INPUT , ASSIGN_ID , and ASSIGN_UUID for different primary‑key strategies.
2.2 CRUD
Define a service interface extending IService and an implementation extending ServiceImpl :
public interface IUserService extends IService
{}
public class UserServiceImpl extends ServiceImpl
implements IUserService {}Define a mapper interface extending BaseMapper :
@Mapper
public interface UserMapper extends BaseMapper
{}2.3 Pagination
Add the pagination interceptor configuration:
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 Delete
Configure global logical‑delete fields or use @TableLogic on entity fields:
mybatis-plus:
global-config:
db-config:
logic-delete-field: isDelete
logic-delete-value: 1
logic-not-delete-value: 0 @TableLogic
private Integer isDelete;2.5 Enum Mapping
Implement IEnum for custom enums and configure package scanning:
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum SexEnum implements IEnum
{
MAN(1, "男"),
WOMAN(2, "女");
private Integer code;
private String name;
// getters and getValue()
}Use the enum in the entity:
@TableField("sex")
private SexEnum sex;2.6 Automatic Field Filling
Define a MetaObjectHandler implementation:
@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());
}
}2.7 Multi‑DataSource
Configure multiple masters, slaves, or different database types in application.yml and use the @DS annotation to switch data sources at class or method level:
@DS("slave_1")
public class UserServiceImpl extends ServiceImpl
implements IUserService {
@DS("slave_1")
public List
getList() { return this.list(); }
@DS("master")
public int saveUser(UserDO user) { return this.save(user) ? 1 : 0; }
}3. Testing
Create the user table, implement a REST controller with endpoints for save, update, delete, list, and pagination, and verify that all features work as expected.
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
// endpoints: /save, /update, /delete, /list, /page
}The article also provides links to the full source code repository and additional resources.
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.