MyBatis-Plus 与 Spring Boot 整合及常用功能详解

MyBatis-Plus 与 Spring Boot 整合及常用功能详解

精选文章moguli202025-05-24 18:42:002A+A-


以下是 MyBatis-Plus 与 Spring Boot 整合的详细用法,包含依赖配置、核心配置、代码示例和常用功能演示:

一、添加依赖

在 pom.xml 中引入 MyBatis-Plus 和数据库驱动(以 MySQL 为例):

<dependencies>

<!-- Spring Boot 启动器 -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter</artifactId>

</dependency>

<!-- MyBatis-Plus 核心依赖 -->

<dependency>

<groupId>com.baomidou</groupId>

<artifactId>mybatis-plus-boot-starter</artifactId>

<version>3.5.3</version> <!-- 最新版本请查看官网 -->

</dependency>

<!-- MySQL 驱动(8.x 版本) -->

<dependency>

<groupId>com.mysql</groupId>

<artifactId>mysql-connector-j</artifactId>

<scope>runtime</scope>

</dependency>

<!-- Spring Boot 测试 -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

</dependencies>

二、配置文件(application.yml)

配置数据源和 MyBatis-Plus 的扫描路径、日志等:

spring:

datasource:

driver-class-name: com.mysql.cj.jdbc.Driver # MySQL 8+ 驱动类名

url: jdbc:mysql://localhost:3306/test_db?useSSL=false&serverTimezone=Asia/Shanghai

username: root

password: your_password

# (可选)配置连接池(如 HikariCP)

# hikari:

# minimum-idle: 5

# maximum-pool-size: 15

mybatis-plus:

mapper-locations: classpath:mapper/**/*.xml # Mapper XML 文件路径(可选,复杂查询时使用)

type-aliases-package: com.example.entity # 实体类包路径(自动扫描别名)

configuration:

log-impl:
org.apache.ibatis.logging.stdout.StdOutImpl # 打印 SQL 日志(开发环境使用)

global-config:

db-config:

logic-delete-field: is_deleted # 逻辑删除字段名(全局配置)

logic-delete-value: 1 # 逻辑删除标识:已删除(值)

logic-not-delete-value: 0 # 逻辑删除标识:未删除(值)

三、启动类配置

在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 接口所在的包:

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.mybatis.spring.annotation.MapperScan;

@SpringBootApplication

@MapperScan("com.example.mapper") // 扫描 Mapper 接口包

public class MybatisPlusDemoApplication {

public static void main(String[] args) {

SpringApplication.run(MybatisPlusDemoApplication.class, args);

}

}

四、实体类(Entity)

使用 MyBatis-Plus 注解映射数据库表和字段:

package com.example.entity;

import com.baomidou.mybatisplus.annotation.*;

import lombok.Data;

@Data

@TableName("tb_user") // 映射数据库表名

public class User {

@TableId(type = IdType.AUTO) // 主键策略(自增)

private Long id;

private String name;

private Integer age;

private String email;

// 逻辑删除字段(标记为 @TableLogic)

@TableLogic

private Integer isDeleted;

// 自动填充字段(插入/更新时自动填充)

@TableField(fill = FieldFill.INSERT)

private Date createTime;

@TableField(fill = FieldFill.INSERT_UPDATE)

private Date updateTime;

}

五、Mapper 接口

继承 BaseMapper<T> 接口,自动获得 CRUD 方法:

package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import com.example.entity.User;

public interface UserMapper extends BaseMapper<User> {

// 无需编写基础 CRUD 方法,直接继承 BaseMapper 即可

// 复杂查询可在对应的 XML 中编写

}

六、配置分页插件(MybatisPlusInterceptor)

MyBatis-Plus 3.4.0+ 推荐使用 MybatisPlusInterceptor 配置分页、乐观锁等插件:

package com.example.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;

import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class MyBatisPlusConfig {

// 配置分页插件

@Bean

public MybatisPlusInterceptor mybatisPlusInterceptor() {

MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

// 添加分页插件

interceptor.addInnerInterceptor(new PaginationInnerInterceptor());

// (可选)添加乐观锁插件

// interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

return interceptor;

}

}

七、Service 层使用示例

1. 基础 CRUD 操作

package com.example.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.example.entity.User;

import com.example.mapper.UserMapper;

import org.springframework.stereotype.Service;

@Service

public class UserService extends ServiceImpl<UserMapper, User> {

// 继承 ServiceImpl 后,自动获得基础服务方法(如 save、update、list 等)

// 示例:查询年龄大于 20 且邮箱不为空的用户

public List<User> getUsersByAgeAndEmail() {

LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();

wrapper.gt(User::getAge, 20)

.isNotNull(User::getEmail);

return baseMapper.selectList(wrapper);

}

}

2. 分页查询

@Service

public class UserService {

public Page<User> getUsersByPage(int currentPage, int pageSize) {

Page<User> page = new Page<>(currentPage, pageSize); // currentPage 从 1 开始

baseMapper.selectPage(page, null); // 查询所有数据并分页

return page; // 包含总记录数和当前页数据

}

}

3. 逻辑删除

@Service

public class UserService {

public void deleteUser(Long id) {

baseMapper.deleteById(id); // 逻辑删除(自动更新 is_deleted 为 1)

}

}

八、复杂查询:XML 与 MyBatis-Plus 混合使用

如果需要编写复杂 SQL,可以在 Mapper 接口中声明方法,并在 XML 中实现:

// Mapper 接口声明方法

public interface UserMapper extends BaseMapper<User> {

List<User> selectUsersWithCondition(@Param("age") Integer age);

}

<!-- resources/mapper/UserMapper.xml -->

<mapper namespace="com.example.mapper.UserMapper">

<select id="selectUsersWithCondition" resultType="com.example.entity.User">

SELECT * FROM tb_user

<where>

<if test="age != null">age > #{age}</if>

</where>

</select>

</mapper>

九、常用功能总结

功能

实现方式

基础 CRUD

继承 BaseMapper 或 ServiceImpl,直接调用 selectById、insert 等方法

条件查询

使用 QueryWrapper 或 LambdaQueryWrapper 构建动态条件

分页查询

配置
PaginationInnerInterceptor,使用 Page 对象

逻辑删除

实体类字段添加 @TableLogic,全局配置逻辑删除值

自动填充

配置 MetaObjectHandler,实现字段插入 / 更新时自动填充时间等信息

乐观锁

添加
OptimisticLockerInnerInterceptor 插件,实体类字段添加 @Version

十、测试验证

在测试类中注入 Service 并验证功能:

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

import com.example.entity.User;

import com.example.service.UserService;

@SpringBootTest

public class UserServiceTest {

@Autowired

private UserService userService;

@Test

public void testInsertUser() {

User user = new User();

user.setName("张三");

user.setAge(25);

user.setEmail("zhangsan@example.com");

boolean result = userService.save(user);

System.out.println("插入结果:" + result);

}

}

通过以上步骤,即可完成 MyBatis-Plus 与 Spring Boot 的整合,并利用其特性大幅简化数据库操作。MyBatis-Plus 在保留 MyBatis 灵活性的同时,减少了基础代码的编写量,适合快速开发场景。

点击这里复制本文地址 以上内容由莫古技术网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

莫古技术网 © All Rights Reserved.  滇ICP备2024046894号-2