当前位置: 首页 > news >正文

MybatisPlus入门指南

MyBatis-Plus 是一个 MyBatis 的增强工具,在 Myatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

(一)快速入门

  1. 导入依赖

    <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>
    
  2. 编写dao层

    @Mapper
    public interface StudentDao extends BaseMapper<Student> {
    }
    
  3. 测试

    @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() 获取总页数等)。
  1. 导入分页插件依赖(高版本需要手动导入)

    <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.6</version> <!-- 推荐使用3.5.x+版本(支持Spring Boot 3.x) -->
    </dependency>
    
  2. 配置mybatisplus配置文件

    @Configuration
    public class MpConfig {@Beanpublic MybatisPlusInterceptor MpInterceptor(){MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor() );return mpInterceptor;}
    }
    
  3. 代码

        @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 表达式 (强烈推荐!): 使用 LambdaQueryWrapperLambdaUpdateWrapper,避免硬编码字段名,编译时检查,更安全更优雅。
@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;
@SqlParserMapper 方法/接口filter:是否过滤 SQL 解析(3.1.1+已弃用) 控制是否跳过 SQL 解析(如多租户场景)@SqlParser(filter = true)
@InterceptorIgnoreMapper 方法多个属性如 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操作

  1. 根据字段配置

    @TableLogic(value = "0",delval = "1")
    private int deleted;
    
  2. 全局配置

    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 插件

  1. 读取记录时,获取当前的版本号(version)。
  2. 在更新记录时,将这个版本号一同传递。
  3. 执行更新操作时,设置 version = newVersion 的条件为 version = oldVersion
  4. 如果版本号不匹配,则更新失败。
@Test
void testOptimisticLocker(){Student student = studentDao.selectById("20250001");Student student2 = studentDao.selectById("20250001");student.setMajor("大数据");studentDao.updateById(student);student2.setMajor("软工");studentDao.updateById(student);
}
http://www.xdnf.cn/news/1168453.html

相关文章:

  • LeetCode 658.找到K个最接近的元素
  • 豪鹏科技锚定 “AI + 固态” 赛道:从电池制造商到核心能源方案引领者的战略跃迁
  • leetcode 1695. 删除子数组的最大得分 中等
  • 浏览器解码顺序xss
  • 低成本、高泛化能力的无人机自主飞行!VLM-Nav:基于单目视觉与视觉语言模型的无地图无人机导航
  • excle中匹配加密手机号(同sheet中)
  • Springboot + MyBatis-Plus + PageHelper 分页性能混合优化方案
  • 解决栅格数据裁剪矢量数据问题两种方法,ArcGIS解决与PYTHON解决
  • 物联网_TDengine_EMQX_性能测试
  • 【Android】xml和Java两种方式实现发送邮件页面
  • API网关原理与使用场景详解
  • Apache Ignite 中 WHERE 子句中的子查询(Subqueries in WHERE Clause)的执行方式
  • Linux操作系统从入门到实战(十二)Linux操作系统第一个程序(进度条)
  • 北京养老金计算公式网页实现案例:从需求分析到架构设计
  • J2EE模式---前端控制器模式
  • Python 绘制各类折线图全指南:从基础到进阶
  • k8s:离线部署tomcatV11.0.9,报Cannot find /opt/bitnami/tomcat/bin/setclasspath.sh
  • zabbix“专家坐诊”第295期问答
  • 以太网基础⑥ ZYNQ PS端 基于LWIP的TCP例程测试
  • MATLAB软件使用频繁,企业如何做到“少买多用”?
  • MFC类Qt的自动布局框架
  • 力扣-链表相关题 持续更新中。。。。。。
  • UE5 UI ScrollBox 滚动框
  • 欧拉系统二进制部署Docker
  • Linux_Ext系列文件系统基本认识(一)
  • Fluent许可与网络安全策略
  • 【洛谷】用两个数组实现静态单链表、静态双向链表,排队顺序
  • 【C语言进阶】动态内存管理(1)
  • 赋能未来数学课堂——基于Qwen3、LangChain与Agent架构的个性化教辅系统研究
  • Vue + WebSocket 实时数据可视化实战:多源融合与模拟数据双模式设计