3.3、MyBatis Plus集成
分类: 搭建单体商城服务
MyBatis-Plus 集成
MyBatis-Plus 是 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,简化开发、提高效率。本节将学习如何在 Spring Boot 3 中集成 MyBatis-Plus。
本节将学习:MyBatis-Plus 简介、依赖添加、配置类编写,以及基础 CRUD 演示。
MyBatis-Plus 简介
什么是 MyBatis-Plus?
MyBatis-Plus 是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
核心特性
MyBatis-Plus 核心特性:
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响
- 损耗小:启动即会自动注入基本 CRUD,性能基本无损耗
- 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅通过少量配置即可实现单表大部分 CRUD 操作
- 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
- 支持主键自动生成:支持多达 4 种主键策略
- 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
- 支持自定义全局通用操作:支持全局通用方法注入
- 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper、Model、Service、Controller 层代码
- 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,分页插件支持多种数据库
- 内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
依赖添加
Maven 依赖
在 pom.xml 中添加依赖:
<dependencies> <!-- MyBatis-Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.5</version> </dependency> <!-- MySQL Driver --> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency> <!-- Connection Pool --> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> </dependency> </dependencies>
版本说明
MyBatis-Plus 版本选择:
- 3.5.5:支持 Spring Boot 3.x
- 确保与 Spring Boot 版本兼容
配置类编写
数据源配置
application.yml 配置:
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/ecommerce?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai username: root password: your_password hikari: minimum-idle: 5 maximum-pool-size: 20 connection-timeout: 30000 idle-timeout: 600000 max-lifetime: 1800000 mybatis-plus: configuration: map-underscore-to-camel-case: true log-impl: org.apache.ibatis.logging.stdout.StdOutImpl global-config: db-config: id-type: auto logic-delete-field: deleted logic-delete-value: 1 logic-not-delete-value: 0 mapper-locations: classpath*:/mapper/**/*.xml type-aliases-package: com.example.ecommerce.entity
MyBatis-Plus 配置类
package com.example.ecommerce.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 { /** * MyBatis-Plus 拦截器配置 */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // 分页插件 interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } }
基础 CRUD 演示
实体类
package com.example.ecommerce.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 email; private String phone; private String password; private String nickname; private String avatar; private Integer status; private LocalDateTime createTime; private LocalDateTime updateTime; }
Mapper 接口
package com.example.ecommerce.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.ecommerce.entity.User; import org.apache.ibatis.annotations.Mapper; @Mapper public interface UserMapper extends BaseMapper<User> { // BaseMapper 已经提供了基础的 CRUD 方法 // 无需手动编写 SQL }
Service 接口
package com.example.ecommerce.service; import com.baomidou.mybatisplus.extension.service.IService; import com.example.ecommerce.entity.User; public interface UserService extends IService<User> { // IService 已经提供了基础的 CRUD 方法 }
Service 实现
package com.example.ecommerce.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.example.ecommerce.entity.User; import com.example.ecommerce.mapper.UserMapper; import com.example.ecommerce.service.UserService; import org.springframework.stereotype.Service; @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { // ServiceImpl 已经实现了基础的 CRUD 方法 }
CRUD 操作示例
package com.example.ecommerce.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.example.ecommerce.entity.User; import com.example.ecommerce.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserService userService; // 插入 @PostMapping public User create(@RequestBody User user) { userService.save(user); return user; } // 根据 ID 查询 @GetMapping("/{id}") public User getById(@PathVariable Long id) { return userService.getById(id); } // 分页查询 @GetMapping public Page<User> list(@RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) { Page<User> page = new Page<>(current, size); return userService.page(page); } // 条件查询 @GetMapping("/search") public Page<User> search(@RequestParam String keyword, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) { Page<User> page = new Page<>(current, size); QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.like("username", keyword) .or() .like("email", keyword); return userService.page(page, wrapper); } // 更新 @PutMapping("/{id}") public User update(@PathVariable Long id, @RequestBody User user) { user.setId(id); userService.updateById(user); return user; } // 删除 @DeleteMapping("/{id}") public void delete(@PathVariable Long id) { userService.removeById(id); } }
BaseMapper 方法
常用方法
BaseMapper 提供的方法:
int insert(T entity):插入一条记录int deleteById(Serializable id):根据 ID 删除int updateById(T entity):根据 ID 修改T selectById(Serializable id):根据 ID 查询List<T> selectList(Wrapper<T> queryWrapper):查询列表Page<T> selectPage(Page<T> page, Wrapper<T> queryWrapper):分页查询
条件构造器
QueryWrapper 使用
// 等值查询 QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.eq("status", 1); // 模糊查询 wrapper.like("username", "admin"); // 范围查询 wrapper.between("create_time", startTime, endTime); // 排序 wrapper.orderByDesc("create_time"); // 组合条件 wrapper.eq("status", 1) .like("username", "admin") .orderByDesc("create_time");
LambdaQueryWrapper 使用
// 使用 Lambda 表达式,避免字段名写错 LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>(); wrapper.eq(User::getStatus, 1) .like(User::getUsername, "admin") .orderByDesc(User::getCreateTime);
分页插件
分页查询
// 创建分页对象 Page<User> page = new Page<>(1, 10); // 第1页,每页10条 // 执行分页查询 Page<User> result = userService.page(page); // 获取结果 List<User> records = result.getRecords(); // 当前页数据 long total = result.getTotal(); // 总记录数 long pages = result.getPages(); // 总页数
官方资源
- MyBatis-Plus 官方文档:https://baomidou.com/
- MyBatis-Plus GitHub:https://github.com/baomidou/mybatis-plus
- MyBatis-Plus 快速开始:https://baomidou.com/pages/226c21/
本节小结
在本节中,我们学习了:
第一个是 MyBatis-Plus 简介。 MyBatis-Plus 是 MyBatis 的增强工具,简化开发、提高效率。
第二个是依赖添加。 在 pom.xml 中添加 MyBatis-Plus 和 MySQL 驱动依赖。
第三个是配置类编写。 配置数据源和 MyBatis-Plus 拦截器。
第四个是基础 CRUD 演示。 使用 BaseMapper 和 IService 实现基础的 CRUD 操作。
这就是 MyBatis-Plus 集成。通过 MyBatis-Plus,我们可以大大简化数据库操作代码。
在下一节,我们将学习如何设计实体类,使用 Lombok 简化代码。