MyBatis-Plus快速入门指南:零基础学习也能轻松上手
字数 1223 2025-08-18 17:33:40
MyBatis-Plus 全面教学指南
一、MyBatis-Plus 简介
1. 基本概念
MyBatis-Plus (简称 MP) 是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
2. 核心特性
- 无侵入:只做增强不做改变,引入不会对现有工程产生影响
- 损耗小:启动即自动注入基本 CURD,性能基本无损耗
- 强大的 CRUD 操作:内置通用 Mapper、通用 Service
- Lambda 支持:通过 Lambda 表达式编写查询条件
- 主键自动生成:支持 4 种主键策略(含分布式唯一 ID 生成器)
- ActiveRecord 模式:实体类继承 Model 类即可进行 CRUD
- 自定义全局操作:支持全局通用方法注入
- 代码生成器:快速生成 Mapper、Model、Service、Controller
- 分页插件:基于 MyBatis 物理分页,支持多种数据库
- 性能分析插件:输出 SQL 语句及执行时间
- 全局拦截插件:全表 delete/update 操作智能分析阻断
二、快速入门
1. 开发环境准备
- JDK 1.8+
- MySQL 5.7+
- Spring Boot 2.x
2. 数据库准备
CREATE DATABASE `mp_study` DEFAULT CHARACTER SET utf8mb4;
USE `mp_study`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`name` varchar(30) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`email` varchar(50) DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
3. Spring Boot 工程创建
依赖配置
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
配置文件
# DataSource Config
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mp_study?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
username: root
password: 1234
# MyBatis-Plus 配置
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
启动类配置
@MapperScan("com.example.mapper")
@SpringBootApplication
public class MybatisPlusStudyApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusStudyApplication.class, args);
}
}
4. 基础代码编写
实体类
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
Mapper 接口
public interface UserMapper extends BaseMapper<User> {
}
测试用例
@SpringBootTest
class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
void testSelectList() {
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
}
三、基本 CRUD 操作
1. 插入操作
@Test
void testInsert() {
User user = new User(null, "lisi", 22, "aaa@qq.com");
int result = userMapper.insert(user);
System.out.println("受影响行数: " + result);
System.out.println("生成ID: " + user.getId()); // 基于雪花算法生成
}
2. 删除操作
根据 ID 删除
@Test
void testDeleteById() {
int result = userMapper.deleteById(1L);
System.out.println("受影响行数: " + result);
}
批量删除
@Test
void testDeleteBatchIds() {
List<Long> ids = Arrays.asList(2L, 3L, 4L);
int result = userMapper.deleteBatchIds(ids);
System.out.println("受影响行数: " + result);
}
条件删除
@Test
void testDeleteByMap() {
Map<String, Object> map = new HashMap<>();
map.put("age", 22);
map.put("name", "lisi");
int result = userMapper.deleteByMap(map);
System.out.println("受影响行数: " + result);
}
3. 更新操作
@Test
void testUpdateById() {
User user = new User(10L, "hello", 12, null);
int result = userMapper.updateById(user);
System.out.println("受影响行数: " + result);
}
4. 自动填充功能
实体类配置
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
元对象处理器
@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());
}
}
5. 查询操作
基本查询
@Test
void testSelect() {
// 根据ID查询
User user = userMapper.selectById(1L);
// 批量查询
List<User> users = userMapper.selectBatchIds(Arrays.asList(1L, 2L, 3L));
// 条件查询
Map<String, Object> map = new HashMap<>();
map.put("name", "Tom");
List<User> users = userMapper.selectByMap(map);
// 查询所有
List<User> users = userMapper.selectList(null);
}
四、通用 Service 封装
1. Service 接口定义
public interface UserService extends IService<User> {
}
2. Service 实现
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
3. Service 使用示例
查询记录数
@Test
void testGetCount() {
long count = userService.count();
System.out.println("总记录数: " + count);
}
批量插入
@Test
void testSaveBatch() {
ArrayList<User> users = new ArrayList<>();
for (int i = 0; i < 5; i++) {
User user = new User();
user.setName("lyl"+i);
user.setAge(20+i);
users.add(user);
}
userService.saveBatch(users);
}
五、高级特性
1. 条件构造器
@Test
void testQueryWrapper() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper
.select("id", "name", "age")
.like("name", "J")
.between("age", 20, 30)
.orderByDesc("id");
List<User> users = userMapper.selectList(queryWrapper);
users.forEach(System.out::println);
}
2. Lambda 条件构造器
@Test
void testLambdaQueryWrapper() {
LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
lambdaQueryWrapper
.select(User::getId, User::getName, User::getAge)
.like(User::getName, "J")
.between(User::getAge, 20, 30)
.orderByDesc(User::getId);
List<User> users = userMapper.selectList(lambdaQueryWrapper);
users.forEach(System.out::println);
}
3. 分页查询
@Test
void testPage() {
Page<User> page = new Page<>(1, 2); // 当前页,每页大小
IPage<User> userPage = userMapper.selectPage(page, null);
System.out.println("总页数: " + userPage.getPages());
System.out.println("总记录数: " + userPage.getTotal());
userPage.getRecords().forEach(System.out::println);
}
六、代码生成器
1. 添加依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
2. 代码生成器配置
public class CodeGenerator {
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("yourname");
gc.setOpen(false);
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mp_study?useSSL=false");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("1234");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.example");
pc.setModuleName("demo");
mpg.setPackageInfo(pc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setInclude("user"); // 表名
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
// 执行生成
mpg.execute();
}
}
七、最佳实践
-
实体类设计:
- 使用 Lombok 简化代码
- 合理使用自动填充字段
- 遵循 Java 命名规范
-
Mapper 设计:
- 继承 BaseMapper 获取基础 CRUD 能力
- 自定义方法使用 @Mapper 注解
- 复杂查询使用 XML 配置
-
Service 设计:
- 继承 IService 获取通用服务能力
- 业务逻辑放在 Service 层
- 事务管理使用 @Transactional
-
性能优化:
- 合理使用索引
- 避免全表扫描
- 使用分页查询大数据集
- 启用 SQL 日志分析慢查询
-
安全考虑:
- 使用参数化查询防止 SQL 注入
- 启用全表操作阻断插件
- 敏感数据加密存储
MyBatis-Plus 通过简化 CRUD 操作、提供丰富的功能插件和代码生成工具,可以显著提高开发效率。合理运用其特性,可以在保证性能的同时减少样板代码,让开发者更专注于业务逻辑的实现。