Master MyBatis-Plus in Spring Boot: Quick Start, Configuration, and Advanced Features
This guide walks through integrating MyBatis-Plus with Spring Boot, covering environment setup, Maven dependencies, configuration of data sources, entity annotations, CRUD services, pagination, logical deletion, enum handling, automatic field filling, multi‑data‑source strategies, and testing with full code examples.
Quick Start
Assumes a Spring Boot project built with Maven, JDK 1.8 and MySQL. The core steps focus on integrating MyBatis‑Plus.
<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>
<!-- Multi‑data‑source support -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>Configuration Preparation
Add @MapperScan to 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 a primary‑master and a slave datasource in application.yml (both point to the same DB for the demo):
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: 123456The default connection pool is HikariCP. Recommended Hikari settings to avoid connection‑lifetime exceptions:
spring:
datasource:
dynamic:
hikari:
max-lifetime: 1800000
connection-timeout: 5000
idle-timeout: 3600000
max-pool-size: 12
min-idle: 4
connection-test-query: /**ping*/Start the Service
Run the Spring Boot application; a successful start is indicated by the console output.
Usage
Entity Annotations
MyBatis‑Plus provides several annotations to simplify mapping. Example entity:
@TableName(value = "user")
public class UserDO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("nickname")
private String nickname;
private String realName;
}Key annotations and typical values:
@TableName : specifies the table name.
@TableId : primary key. IdType options:
AUTO – database auto‑increment.
NONE – follow global setting (default INPUT).
INPUT – user‑provided ID.
ASSIGN_ID – Snowflake algorithm when ID is null.
ASSIGN_UUID – UUID string when ID is null.
@TableField : maps a field to a column and can define query conditions. Example condition constants:
EQUAL – "%s=#{%s}"
NOT_EQUAL – "%s<>#{%s}"
LIKE – "%s LIKE CONCAT('%%',#{%s},'%%')"
LIKE_LEFT – "%s LIKE CONCAT('%%',#{%s})"
LIKE_RIGHT – "%s LIKE CONCAT(#{%s},'%%')"
@TableLogic : logical delete flag.
@TableField(fill = FieldFill.INSERT) : automatic field filling on insert.
CRUD
Service layer extends IService<UserDO>:
import com.baomidou.mybatisplus.extension.service.IService;
import com.wjbgn.user.entity.UserDO;
public interface IUserService extends IService<UserDO> {}Implementation inherits ServiceImpl:
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjbgn.user.entity.UserDO;
import com.wjbgn.user.mapper.UserMapper;
import com.wjbgn.user.service.IUserService;
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements IUserService {}Mapper simply extends BaseMapper<UserDO>:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wjbgn.user.entity.UserDO;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<UserDO> {}Pagination
Add the pagination interceptor to the Spring context:
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;
}
}Logical Delete Configuration
Global configuration in application.yml:
mybatis-plus:
global-config:
db-config:
logic-delete-field: isDelete
logic-delete-value: 1
logic-not-delete-value: 0Or annotate the field directly:
@TableLogic
private Integer isDelete;Enum Mapping
Define an enum that implements IEnum<Integer> and annotate with @JsonFormat so the front‑end receives the name instead of the enum constant:
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; }
}Entity field uses the enum:
@TableField(value = "sex")
private SexEnum sex;Configure package scanning for enums:
mybatis-plus:
typeEnumsPackage: com.wjbgn.*.enumsAutomatic Field Filling
Implement MetaObjectHandler to set timestamps automatically:
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 field declaration:
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;Multiple Data Sources
Three YAML examples illustrate master‑slave, heterogeneous databases, and mixed configurations. The @DS annotation can be placed on classes or methods; method‑level annotation takes precedence.
@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 userDO) { return this.save(userDO) ? 1 : 0; }
}Testing
Create the user table (UTF‑8mb4 charset to store emojis):
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 AUTO_INCREMENT=50 DEFAULT CHARSET=utf8mb4;Controller exposing CRUD and pagination endpoints:
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
@RequestMapping("/save")
public boolean save() {
UserDO userDO = new UserDO();
userDO.setNickname("大漂亮");
userDO.setSex(SexEnum.MAN);
return userService.save(userDO);
}
@RequestMapping("/update")
public boolean update(@RequestParam String nickname, @RequestParam Long id) {
UserDO userDO = new UserDO();
userDO.setNickname(nickname);
userDO.setId(id);
return userService.updateById(userDO);
}
@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 page(@RequestParam int current, @RequestParam int size) {
return userService.page(new Page<>(current, size), new QueryWrapper(new UserDO()));
}
}Running the application and invoking the endpoints confirms that MyBatis‑Plus functions correctly. The full source code is hosted at https://gitee.com/wei_rong_xin/rob-necessities.git.
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 Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow 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.
