当前位置: 首页 > 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.dtcms.com/a/292854.html

相关文章:

  • SonarQube 代码分析工具
  • docker 中安装 ONLYOFFICE 服务
  • C++基础学习——文件操作详解
  • netframe4.5 的mvc 框架 layui 组件的引用
  • 模运算常见定律
  • .net 警告【代码 CS1998】此异步方法缺少 “await“ 运算符,将以同步方式运行。
  • Linux命令集锦-个人整理(偏向进程和端口的查询)
  • CS231n-2017 Lecture5卷积神经网络笔记
  • 如何把jar包打成docker镜像(SpringBoot项目打包成Docker )部署到Linux
  • CMOS知识点 离子注入工艺
  • OpenCV Mat UMat GpuMat Matx HostMem InputArray等设计哲学
  • Arduino学习笔记【快速入门】
  • 蓝牙通信架构(Bluetooth/BLE)
  • Windows系统暂停更新工具
  • 每日面试题12:JVM垃圾回收机制
  • 分布式数据库中间件ShardingSphere
  • Unity UI的未来之路:从UGUI到UI Toolkit的架构演进与特性剖析(1)
  • Java学习-----Bean
  • Datawhale AI 夏令营-心理健康Agent开发学习-Task1
  • 猎板 PCB:多场景适配下印制线路板的材料选择优化策略
  • 朴素贝叶斯算法原理与案例解析
  • linux: tar解压之后属主和属组不是当前用户问题
  • 2025人形机器人动捕技术研讨会即将于7月31日盛大开启
  • 阿里巴巴视觉算法面试30问全景精解
  • 知识库搭建之Meilisearch‘s 搜索引擎-创建搜索引擎项目 测评-东方仙盟测评师
  • 数据降噪/生物信号强化/缓解 dropout,深度学习模型 SUICA 实现空间转录组切片中任一位置基因表达的预测
  • [LLM]Synthetic Visual Genome
  • GNU到底是什么,与Unix和Linux是什么关系
  • 链表经典算法题
  • web复习