MybatisPlus入门指南
MyBatis-Plus 是一个 MyBatis 的增强工具,在 Myatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
(一)快速入门
-
导入依赖
<dependencies><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>3.0.4</version></dependency><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter-test</artifactId><version>3.0.4</version><scope>test</scope></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.6</version> <!-- 推荐使用3.5.x+版本(支持Spring Boot 3.x) --></dependency><!-- Druid 连接池 --><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.2.20</version></dependency><!-- MySQL 驱动 --><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency><!-- 简化实体类开发的java库 --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>provided</scope></dependency></dependencies>
-
编写dao层
@Mapper public interface StudentDao extends BaseMapper<Student> { }
-
测试
@SpringBootTest class Springboot03MybatispulsApplicationTests {@Autowiredprivate StudentDao studentDao;@Testvoid getAll() {List<Student> students = studentDao.selectList(null);System.out.println(students);}@Testvoid getById(){Student student = studentDao.selectById("20250001");System.out.println(student);}@Testvoid testInsert(){Student student = new Student();student.setId("20250016");student.setMajor("软件工程");student.setName("田七");student.setGender('男');student.setCollege("人工智能学院");student.setClassName("软工二班");studentDao.insert(student);}@Testvoid testUpdate(){Student student = new Student();student.setId("20250016");student.setMajor("大数据");studentDao.updateById(student);}@Testvoid testDelete(){studentDao.deleteById("20250016");}}
(二)CRUD
mybatis-plus里面内置基础的CRUD的方法
分页查询
- 创建
Page
对象 (Page<User> page = new Page<>(current, size);
)。 - 调用 Mapper 的
selectPage(page, queryWrapper)
方法。 - 结果存储在
page
对象中 (page.getRecords()
获取记录列表,page.getTotal()
获取总数,page.getPages()
获取总页数等)。
-
导入分页插件依赖(高版本需要手动导入)
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.6</version> <!-- 推荐使用3.5.x+版本(支持Spring Boot 3.x) --> </dependency>
-
配置mybatisplus配置文件
@Configuration public class MpConfig {@Beanpublic MybatisPlusInterceptor MpInterceptor(){MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor() );return mpInterceptor;} }
-
代码
@Testvoid testPageSelect(){IPage iPage = new Page(1,2);IPage page = studentDao.selectPage(iPage, null);System.out.println( "一共多少页:" + page.getPages());System.out.println( "当前页面" + page.getCurrent());System.out.println( "当前页的数据:" + page.getRecords());System.out.println( "每页显示多少数据:" + page.getSize());System.out.println( "一共多少数据:" + page.getTotal());}
注意:开启mybatis-plus日志功能
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
(三)DQL编程控制
条件构造器 (Wrapper
)
条件构造器 | MyBatis-Plus
条件构造器 (Wrapper
): 这是 MP 的灵魂功能!
QueryWrapper
:用于 SELECT 语句的条件构造。UpdateWrapper
:用于 UPDATE 语句的条件构造和 SET 操作。- 核心方法:
eq
/ne
:等于 / 不等于gt
/ge
/lt
/le
:大于 / 大于等于 / 小于 / 小于等于 (根据英文记忆,lt : less than ,gt:great than)between
/notBetween
:在…之间 / 不在…之间like
/notLike
/likeLeft
/likeRight
:模糊查询isNull
/isNotNull
:为空 / 不为空in
/notIn
:在…集合内 / 不在…集合内groupBy
/orderByAsc
/orderByDesc
:分组、排序or
/and
:连接条件 (注意默认是and
)select
:指定查询字段set
(UpdateWrapper
):指定 SET 的字段和值
- Lambda 表达式 (强烈推荐!): 使用
LambdaQueryWrapper
和LambdaUpdateWrapper
,避免硬编码字段名,编译时检查,更安全更优雅。
@Test
void testQueryWrapper(){// 方式一:条件查询QueryWrapper qw = new QueryWrapper();qw.eq("gender","男");List students = studentDao.selectList(qw);System.out.println(students);// 方式二:Lambda表达式条件 (避免表格字段硬编码)QueryWrapper<Student> qw = new QueryWrapper<Student>();qw.lambda().eq(Student::getGender,"男");List<Student> students = studentDao.selectList(qw);System.out.println(students);// 方式三:简化LambdaQueryWrapper<Student> lqw = new LambdaQueryWrapper<Student>();lqw.eq(Student::getGender,"女");List<Student> students = studentDao.selectList(lqw);System.out.println(students);// 方式四:多条件LambdaQueryWrapper<Student> lqw = new LambdaQueryWrapper<Student>();lqw.ne(Student::getGender,"女").ne(Student::getGender,"男");List<Student> students = studentDao.selectList(lqw);System.out.println(students);// 方式五:处理空值boolean condition = false;LambdaQueryWrapper<Student> lqw = new LambdaQueryWrapper<Student>();lqw.ne(condition,Student::getGender,"女");lqw.ne(Student::getGender,"男");List<Student> students = studentDao.selectList(lqw);System.out.println(students);}
注解配置
注解名称 | 作用位置 | 关键属性 | 功能说明 | 示例 |
---|---|---|---|---|
@TableName | 实体类 | value :表名schema :数据库schema | 指定实体类对应的数据库表名 (默认按驼峰转下划线规则匹配表名) | @TableName("sys_user") |
@TableId | 实体类主键字段 | value :主键字段名 type :主键策略 | 标识主键字段并指定生成策略 (主键策略:IdType.AUTO /ASSIGN_ID /INPUT 等) | @TableId(type = IdType.ASSIGN_ID) |
@TableField | 实体类非主键字段 | value :字段名 exist :是否为表字段 fill :自动填充策略 condition :条件预处理 | 字段映射与高级控制 (解决字段名不一致、逻辑删除、自动填充等场景) | @TableField(value = "email", fill = FieldFill.INSERT_UPDATE) |
@Version | 实体类字段 | - | 标识乐观锁版本号字段 (需配合 OptimisticLockerInnerInterceptor 插件) | @Version private Integer version; |
@EnumValue | 枚举类属性 | - | 标记枚举值与数据库存储值的映射属性 (如将枚举的 code 属性存入数据库) | public enum Status { @EnumValue ENABLED(1), ... } |
@TableLogic | 实体类字段 | value :未删除值 delval :删除值 | 标识逻辑删除字段 (删除时自动更新该字段,查询自动过滤已删除数据) | @TableLogic(delval = "1", value = "0") private Integer deleted; |
@SqlParser | Mapper 方法/接口 | filter :是否过滤 SQL 解析 | (3.1.1+已弃用) 控制是否跳过 SQL 解析(如多租户场景) | @SqlParser(filter = true) |
@InterceptorIgnore | Mapper 方法 | 多个属性如 tenantLine /blockAttack 等 | 忽略特定拦截器 (如忽略租户拦截器、攻击SQL阻断器等) | @InterceptorIgnore(tenantLine = "true") |
@KeySequence | 实体类 | value :序列名 dbType :数据库类型 | 指定主键序列(Oracle/PostgreSQL等) 配合 @TableId(type = IdType.INPUT) 使用 | @KeySequence("seq_user_id") @TableId(type = IdType.INPUT) |
# 全局配置
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImplglobal-config:db-config:id-type: autotable-prefix: tb_
逻辑删除
-
逻辑删除功能主要用于避免在数据库中物理删除数据,而是通过更新一个特定的状态字段(如
deleted
)来标记该记录为“已删除”状态。 -
主要思路就是添加一个字段表示该数据是否删除,用@TableLogic进行标记,最后所以删除操作都变成了update操作
-
根据字段配置
@TableLogic(value = "0",delval = "1") private int deleted;
-
全局配置
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImplglobal-config:db-config:id-type: autotable-prefix: tb_logic-delete-field: deletedlogic-delete-value: 0logic-not-delete-value: 1
乐观锁
乐观锁是一种并发控制机制,用于确保在更新记录时,该记录未被其他事务修改。MyBatis-Plus 提供了 OptimisticLockerInnerInterceptor
插件
- 读取记录时,获取当前的版本号(version)。
- 在更新记录时,将这个版本号一同传递。
- 执行更新操作时,设置
version = newVersion
的条件为version = oldVersion
。 - 如果版本号不匹配,则更新失败。
@Test
void testOptimisticLocker(){Student student = studentDao.selectById("20250001");Student student2 = studentDao.selectById("20250001");student.setMajor("大数据");studentDao.updateById(student);student2.setMajor("软工");studentDao.updateById(student);
}