Master MyBatis-Plus with Spring Boot: Complete Guide to CRUD, Pagination, and Multi‑DataSource
This tutorial walks through integrating MyBatis-Plus into a Spring Boot project, covering dependency setup, configuration, entity annotations, CRUD service and mapper usage, pagination, logical deletion, enum handling, automatic field filling, and multi‑data‑source management, complete with code examples and testing.
Quick Start
This article introduces MyBatis-Plus for Spring Boot, covering dependency setup, configuration, and common usage.
1. 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>2. Configuration
Configure the Spring Boot main class, data source properties, and MyBatis‑Plus interceptor for pagination.
@SpringBootApplication
@EnableDiscoveryClient
@MapperScan("com.wjbgn.user.mapper")
public class RobNecessitiesUserApplication {
public static void main(String[] args) {
SpringApplication.run(RobNecessitiesUserApplication.class, args);
}
} 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 @Configuration
@MapperScan("com.wjbgn.*.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}3. Entity Annotations
@TableName("user")
public class UserDO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("nickname")
private String nickname;
@TableField("sex")
private SexEnum sex;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
}4. CRUD Service and Mapper
public interface IUserService extends IService<UserDO> {} @Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements IUserService {} @Mapper
public interface UserMapper extends BaseMapper<UserDO> {}5. Pagination
Page<UserDO> page = userService.page(new Page<>(current, size), new QueryWrapper<>(new UserDO()));6. Logical Delete
@TableLogic
private Integer isDelete; mybatis-plus:
global-config:
db-config:
logic-delete-field: isDelete
logic-delete-value: 1
logic-not-delete-value: 07. Enum Mapping
@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; }
} mybatis-plus:
type-enums-package: com.wjbgn.*.enums8. Automatic Field Fill
@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());
}
}9. Multi‑DataSource
Define multiple master/slave data sources in application.yml and use @DS("slave_1") on service methods to switch.
10. Testing Controller
@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);
}
// other CRUD endpoints omitted for brevity
}After following the steps, the application runs successfully and demonstrates the main features of MyBatis‑Plus.
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 Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
