前言
在 Web 应用项目开发中,持久层数据操作是核心环节之一。传统的 MyBatis 需要编写大量的 XML 映射文件和 SQL 语句,效率较低;而 MyBatis-Plus(简称 MP)作为 MyBatis 的增强工具,在保留 MyBatis 原有特性的基础上,实现了'无 SQL'式的 CRUD 操作,极大简化了数据库开发流程。本文将结合 Web 开发的实战场景,从开发环境配置、SpringBoot 项目搭建、MyBatis-Plus 整合到实战 CRUD,完整讲解如何快速实现 SpringBoot+MyBatis-Plus 的数据库操作。
一、开发环境配置(基础准备)
在开始项目开发前,需先配置好核心开发环境,本次实战使用的环境版本如下(推荐使用稳定版本):
- JDK:1.8(Java 8,Web 开发主流版本)
- Maven:3.8.6(项目构建和依赖管理工具)
- IDEA:2022.3(IntelliJ IDEA Ultimate,Java 开发首选 IDE)
- MySQL:8.0.32(关系型数据库)
1.1 JDK 安装与环境变量配置
步骤 1:下载 JDK
进入 Oracle 官网(或国内镜像站)下载 JDK 1.8 安装包,根据系统选择 Windows/x64 版本,双击安装(建议安装路径:D:\Java\jdk1.8.0_381,避免中文和空格)。

步骤 2:配置环境变量
右键'此电脑'→'属性'→'高级系统设置'→'环境变量',进行如下配置:
- 新建系统变量:
JAVA_HOME,值为 JDK 安装路径(如 D:\Java\jdk1.8.0_381);
- 编辑系统变量
Path,新增:%JAVA_HOME%\bin 和 %JAVA_HOME%\jre\bin;
- 验证:打开 CMD,输入
java -version,若显示 JDK 1.8 版本信息,说明配置成功。


1.2 Maven 配置(IDEA 集成)
步骤 1:下载并解压 Maven
下载 Maven 3.8.6 压缩包,解压到指定路径(如 D:\apache-maven-3.8.6)。
步骤 2:配置 Maven 镜像(加速依赖下载)
修改 Maven 的 conf/settings.xml 文件:
- 配置本地仓库路径:
<localRepository>D:\maven-repo</localRepository>(自定义本地仓库位置);
- 配置阿里云镜像(替换默认中央仓库):
<mirrors>
<mirror>
<id>aliyunmaven</id>
<mirrorOf>central</mirrorOf>
<url>https://maven.aliyun.com/repository/public</url>
</mirror>
</mirrors>
步骤 3:IDEA 中配置 Maven
打开 IDEA→'File'→'Settings'→'Build, Execution, Deployment'→'Build Tools'→'Maven':
- Maven home path:选择解压后的 Maven 路径;
- User settings file:选择修改后的
settings.xml;
- Local repository:选择配置的本地仓库路径。
二、快速搭建 SpringBoot 项目(核心步骤)
使用 IDEA 的 Spring Initializr 快速搭建 SpringBoot 项目,版本选择 2.7.12(推荐稳定版本)。
2.1 创建 SpringBoot 项目
步骤 1:新建项目
打开 IDEA→'New Project'→选择'Spring Initializr'→配置项目信息:
- Name:
springboot-mp-demo(项目名);
- Type:Maven Project;
- Language:Java;
- Group:
com.example;
- Artifact:
springboot-mp-demo;
- Java Version:8;
步骤 2:选择核心依赖
在'Dependencies'页面,勾选以下依赖(Web 开发核心):
- Spring Web(Web 应用基础);
- MySQL Driver(MySQL 数据库驱动);
- Lombok(简化实体类编写);
点击'Create'完成项目创建,IDEA 会自动下载依赖并初始化项目结构。
2.2 项目结构说明(项目重点)
搭建完成后的项目核心结构如下:
springboot-mp-demo
├── src/main/java/com/example/springbootmpdemo
│ ├── SpringbootMpDemoApplication.java
│ ├── entity
│ ├── mapper
│ └── service
└── src/main/resources
├── application.yml
└── static/templates // 静态资源/视图层(本次暂不涉及)
三、整合 MyBatis-Plus(核心实战)
3.1 引入 MyBatis-Plus 依赖
修改 pom.xml 文件,添加 MyBatis-Plus 的核心依赖(注意版本和 SpringBoot 匹配):
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
添加完成后,点击 IDEA 的'Reload All Maven Projects'刷新依赖。
3.2 配置数据库连接与 MyBatis-Plus
修改 src/main/resources/application.yml 文件,配置数据库连接和 MyBatis-Plus 核心参数:
server:
port: 8080
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mp_demo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: root
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.springbootmpdemo.entity
注意:需先在 MySQL 中创建数据库 mp_demo(执行 CREATE DATABASE mp_demo;),无需提前建表(后续用 MP 自动生成)。
3.3 编写实体类(Entity)
以常见的'用户表'为例,在 entity 包下创建 User.java:
package com.example.springbootmpdemo.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String userName;
private String password;
private Integer age;
private LocalDateTime createTime;
}
说明:@Data 注解由 Lombok 提供,可省去手动编写 get/set 方法;@TableName 指定实体类对应的数据表名;@TableId 指定主键策略(AUTO 为自增)。
3.4 编写 Mapper 接口(核心:无需写 SQL)
在 mapper 包下创建 UserMapper.java,继承 MyBatis-Plus 的 BaseMapper:
package com.example.springbootmpdemo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springbootmpdemo.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
核心亮点:继承 BaseMapper<User> 后,MP 会自动为 User 实体生成对应的 CRUD SQL,无需编写 XML 或注解 SQL,这是 MP 最核心的简化点。
3.5 启动类添加 Mapper 扫描
修改项目启动类 SpringbootMpDemoApplication.java,添加 @MapperScan 注解,扫描 Mapper 接口所在包:
package com.example.springbootmpdemo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.springbootmpdemo.mapper")
public class SpringbootMpDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMpDemoApplication.class, args);
}
}
四、实战:MyBatis-Plus 实现 CRUD 操作
接下来通过 IDEA 的测试类,验证 MP 的 CRUD 功能,这也是 Web 开发中最核心的实战环节。
4.1 创建测试类
在 src/test/java/com/example/springbootmpdemo 下,创建 UserMapperTest.java:
package com.example.springbootmpdemo;
import com.example.springbootmpdemo.entity.User;
import com.example.springbootmpdemo.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.time.LocalDateTime;
import java.util.List;
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testInsert() {
User user = new User();
user.setUserName("张三");
user.setPassword("123456");
user.setAge(20);
user.setCreateTime(LocalDateTime.now());
int rows = userMapper.insert(user);
System.out.println("新增成功,受影响行数:" + rows);
System.out.println("新增用户的 ID:" + user.getId());
}
@Test
public void testSelectList() {
List<User> userList = userMapper.selectList();
userList.forEach(user -> System.out.println(user));
}
{
();
user.setId();
user.setAge();
userMapper.updateById(user);
System.out.println( + rows);
}
{
userMapper.deleteById();
System.out.println( + rows);
}
}
4.2 运行测试并验证结果
步骤 1:运行新增测试(testInsert)
- 查看 MySQL 的
user 表,会新增一条用户数据,ID 自动自增。
执行 testInsert 方法,控制台会打印 MP 自动生成的 INSERT SQL:
INSERT INTO user (
user_name,
password,
age,
create_time
) VALUES (?, ?, ?, ?)
步骤 2:运行查询 / 更新 / 删除测试
依次执行 testSelectList、testUpdate、testDelete 方法,控制台会打印对应的 SQL 和执行结果,验证所有 CRUD 操作均可正常执行。
五、进阶:MyBatis-Plus 分页插件(拓展阅读)
在 Web 项目中,分页查询是高频需求,MP 提供了开箱即用的分页插件,配置和使用都非常简单。
5.1 配置分页插件
在项目中创建 config 包,新增 MyBatisPlusConfig.java:
package com.example.springbootmpdemo.config;
import com.baomidou.mybatisplus.annotation.DbType;
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(DbType.MYSQL));
return interceptor;
}
}
5.2 测试分页查询
在测试类中新增分页测试方法:
@Test
public void testPage() {
Page<User> page = new Page<>(1, 2);
userMapper.selectPage(page, null);
System.out.println("总记录数:" + page.getTotal());
System.out.println("总页数:" + page.getPages());
System.out.println("当前页数据:");
page.getRecords().forEach(user -> System.out.println(user));
}
运行该方法,控制台会打印分页 SQL(包含 LIMIT),并输出分页结果,验证分页功能生效。
六、核心总结与拓展
6.1 核心总结
- SpringBoot 整合 MyBatis-Plus 的核心是引入依赖 + 配置数据库 + 继承 BaseMapper,无需编写基础 CRUD 的 SQL;
- Lombok 的
@Data 注解可大幅简化实体类编写,MP 的 @TableName、@TableId 等注解用于关联数据库表;
- MP 的分页插件只需简单配置,即可实现开箱即用的分页功能,提升开发效率。
6.2 项目拓展(Web 项目实战)
在实际 Web 应用开发中,可基于本次整合的基础,进一步实现:
- 编写 Service 层封装业务逻辑;
- 编写 Controller 层提供接口,结合 Postman 测试;
- 整合 Thymeleaf 实现视图层展示用户数据;
- 添加全局异常处理、参数校验等功能,完善项目。
结尾
本文结合 Web 应用项目开发的实战需求,从环境配置到项目搭建,再到 MyBatis-Plus 的整合与实战,完整讲解了 SpringBoot+MyBatis-Plus 的核心使用方式。相比于传统 MyBatis,MP 极大降低了持久层开发的工作量,非常适合中小型 Web 应用开发。