Comprehensive Guide to Integrating MyBatis-Plus with Spring Boot

This article provides a step‑by‑step tutorial on integrating MyBatis‑Plus into a Spring Boot project, covering dependency setup, configuration of data sources, entity annotations, CRUD operations, pagination, logical deletion, enum handling, automatic field filling, and multi‑datasource usage with complete code examples.

Architecture Digest
Architecture Digest
Architecture Digest
Comprehensive Guide to Integrating MyBatis-Plus with Spring Boot

The article introduces MyBatis-Plus, a powerful ORM plugin for Spring Boot, and outlines a complete workflow from environment preparation to advanced features.

1. Quick Start

Prepare a Spring Boot project with JDK 1.8, Maven, and MySQL. Create the database and set the character set to utf8mb4 for emoji support.

1.1 Dependency Preparation

<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>

1.2 Configuration

Application entry class scans mappers:

@EnableDiscoveryClient
@MapperScan("com.wjbgn.user.mapper")
@SpringBootApplication
public class RobNecessitiesUserApplication {
    public static void main(String[] args) {
        SpringApplication.run(RobNecessitiesUserApplication.class, args);
    }
}

YAML data‑source configuration with a master‑slave setup (both point to the same DB in the example):

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

HikariCP pool tuning (optional):

spring:
  datasource:
    dynamic:
      hikari:
        max-lifetime: 1800000
        connection-timeout: 5000
        idle-timeout: 3600000
        max-pool-size: 12
        min-idle: 4
        connection-test-query: /**ping*/

1.3 Service Layer CRUD

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 {}

1.4 Mapper Layer CRUD

@Mapper
public interface UserMapper extends BaseMapper<UserDO> {}

2. Advanced Features

2.1 Pagination – add the MyBatis‑Plus interceptor:

@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.2 Logical Deletion – global config or @TableLogic annotation:

mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: isDelete
      logic-delete-value: 1
      logic-not-delete-value: 0
@TableLogic
private Integer isDelete;

2.3 Enum Mapping – implement IEnum and use @JsonFormat for JSON output:

@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; }
}

Entity field:

@TableField("sex")
private SexEnum sex;

2.4 Automatic Field Filling – implement MetaObjectHandler:

@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 annotation:

@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;

2.5 Multi‑DataSource – configure multiple masters/slaves or different DB types in application.yml and use @DS("slave_1") on services or methods.

@DS("slave_1")
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements IUserService { ... }

3. Testing

After the configuration, the article shows how to create the user table, implement a REST controller with endpoints for save, update, delete, list, and paginated queries, and verifies that all operations work correctly.

The tutorial demonstrates that MyBatis‑Plus greatly simplifies CRUD development in Spring Boot while providing powerful extensions such as pagination, logical deletion, enum conversion, automatic timestamp handling, and flexible multi‑datasource management.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpring BootORMmybatis-plusCRUD
Architecture Digest
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.