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

MybatisPlus操作方法详细总结

摘要:本文围绕 MyBatis-Plus 数据操作展开,涵盖标准数据层 CRUD 与分页查询;以及各种的复杂 SQL 查询映射匹配(@TableField、@TableName 注解)与 ID 生成策略(@TableId 五种类型及全局配置);多数据批量操作,以及逻辑删除(标记字段、注解、配置)和乐观锁(字段、注解、拦截器)机制,全面介绍 MP 核心数据操作功能。

思维导图

1. 标准数据层CRUD分页查询

基础增删改查

    //新增方法    @Testvoid testSave() {User user=new User();user.setId(1L);user.setUsername("tom");userMapper.insert(user);}//删除方法@Testvoid testDelete(int id) {userMapper.deleteById(id);}//修改方法@Testvoid testUpdateById() {User user=new User();user.setId(1L);user.setUsername("Tom");userMapper.updateById(user);}//根据id查询数据@Testvoid testGetById(int id) {userMapper.selectById(id);}//查询全部@Testvoid testGetAll() {List<User> userList = userMapper.selectList(null);System.out.println(userList);}

分页查询

1.配置MP拦截器

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

2.分页查询业务代码

//分页查询@Testvoid testSelectPage() {int current = 1;int size = 2;IPage page = new Page(current, size);userMapper.selectPage(page,null);System.out.println("当前页码值:"+page.getCurrent());System.out.println("每页显示数:"+page.getSize());System.out.println("一共多少页:"+page.getPages());System.out.println("一共多少条:"+page.getTotal());System.out.println("所有记录数:"+page.getRecords());}

3.开启MP日志(推荐开启)

mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

返回结果

2. 复杂SQL查询方法合集(Wrapper)

MyBatisPlus将书写复杂的SQL查询条件进行了封装,使用编程的形式完成查询条件的组合

1.条件查询 - 设置查询条件

    //按条件查询@Testvoid SelectByCondition() {//第一种:间接使用lamda格式按条件查询QueryWrapper<User> wrapper=new QueryWrapper();//设置条件wrapper.lambda().lt(User::getId,2);List<User> userList1 = userMapper.selectList(wrapper);System.out.println(userList1);//第二种:直接使用lamda格式按条件查询LambdaQueryWrapper<User> lqWrapper=new LambdaQueryWrapper<User>();//设置条件lqWrapper.lt(User::getId,2);List<User> userList2 = userMapper.selectList(wrapper);System.out.println(userList2);}

2.条件查询 - 组合条件查询

//按条件查询@Testvoid SelectByCondition() {LambdaQueryWrapper<User> lqWrapper1=new LambdaQueryWrapper<User>();//设置条件(并列关系)lqWrapper1.lt(User::getId,3).gt(User::getId,1);//设置条件(或者关系)lqWrapper1.gt(User::getId,3).or().lt(User::getId,1);//使用betweenlqWrapper1.between(User::getAge,16,24);//模糊查询lqWrapper1.like("userName","o");queryWrapper1.likeLeft("userName","R");queryWrapper1.likeRight("userName","e");}

3.条件查询 - NULL空值

//按条件查询 - 动态SQL@Testvoid SelectByCondition() {//模拟查询请求的数据UserQuery query = new UserQuery();query.setAge(18);query.setId(5L);//null值判定LambdaQueryWrapper<User> lqWrapper = new LambdaQueryWrapper<User>();lqWrapper.gt(query.getAge()!=null,User::getAge,query.getAge());}

4.条件查询 - 查询投影

先按设定条件筛选出满足要求的数据行,再从这些行中提取所需的特定列,最终得到既符合条件限制又仅包含目标字段的数据结果。

查询投影

//条件查询 - 查询投影@Testvoid SelectByCondition() {//写法一:这种写法只适用于LambdaLambdaQueryWrapper<User> lqWrapper = new LambdaQueryWrapper<User>();lqWrapper.select(User::getId,User::getAge,User::getUsername);//写法二:使用两次查询QueryWrapper<User> queryWrapper=new QueryWrapper<>();queryWrapper.select("id","userName","age");//若结果为单个对象,使用selectOneList<User> userList = userMapper.selectList(queryWrapper);}

查询数量,查询分组

//条件查询 - 查询投影@Testvoid SelectByCondition() {//查询数量QueryWrapper<User> queryWrapper=new QueryWrapper<>();queryWrapper.select("count(*) as count");//按年龄分组queryWrapper.groupBy("age");List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);System.out.println(maps);}

3. 映射匹配兼容性

字段映射与表名映射

使用TableField注解解决

1.value属性


2.exist属性


2.select属性


使用TableName注解

4.id生成策略

使用@TableId注解


总共五大ID生成策略

使用方法

@Data
@TableName(value ="user")
public class User {//五选一@TableId(type = IdType.AUTO)@TableId(type = IdType.ASSIGN_ID)@TableId(type = IdType.NONE)@TableId(type = IdType.INPUT)@TableId(type = IdType.ASSIGN_UUID)private Long id;private String username;private Integer age;private String phone;    
}

全局配置方法

全局配置

5.多数据操作 - 删除和查询

    //批量删除@Testvoid testDelete() {List<Long> list=new ArrayList<>();for (long i = 1; i < 5; i++) {list.add(i);}userMapper.deleteBatchIds(list);}//批量查询@Testvoid testDelete() {List<Long> list=new ArrayList<>();for (long i = 1; i < 5; i++) {list.add(i);}userMapper.selectBatchIds(list);}

6.逻辑删除

1.添加逻辑删除标记字段

2.实体类加@TableLogic注解

3.修改配置文件

mybatis-plus:global-config:db-config:logic-delete-field: isDeletelogic-delete-value: 1logic-not-delete-value: 0

7.乐观锁

1.添加锁标记字段

2.添加版本注解

3.配置乐观锁拦截器实现锁机制对应的动态SQL语句拼装


至此,大功告成!🎉🎉🎉

http://www.lryc.cn/news/596973.html

相关文章:

  • CNN实战案例:从图像识别到医疗诊断
  • 19-动态路由
  • QEMU RISCV TCG 详解二 -- RISCV CPU Representation
  • Axios 响应拦截器
  • AI 搜索引擎:让信息“长脑子”而不是“堆数据”
  • 【Spring Cloud Gateway 实战系列】基础篇:路由、断言、过滤器、负载均衡深度解析
  • 【服务器】 MCTP Over PCIe 的内容、用途、工作原理及硬件设计注意事项
  • 基于php的校园招聘平台
  • SpringCloudGateWay 使用nacos网关自动负载均衡
  • 二分查找-162.寻找峰值-力扣(LeetCode)
  • 思路探索:当大型语言模型遇见数据分析的现实挑战
  • 统一服务入口——Spring Cloud Gateway
  • 高亮匹配关键词样式highLightMatchString、replaceHTMLChar
  • Effective Python 第15条 不要过分依赖给字典添加条目时所用的顺序
  • CodeBuddy IDE实战:用AI全栈能力快速搭建课程表网页
  • JavaScript HTTP 请求:从老古董到新潮流
  • 在线深凹槽深检测方法都有哪些 —— 激光频率梳 3D 轮廓检测
  • 如何在Pico等Android头显中实现无人机低延迟RTMP全景巡检画面播放
  • 2025年7月份实时最新获取地图边界数据方法,省市区县街道多级联动【文末附实时geoJson数据下载】
  • 从零开始学习Dify-Excel数据可视化(四)
  • 无人机光伏巡检误检率↓78%!陌讯多模态融合算法实战解析
  • 【Android】用 ViewPager2 + Fragment + TabLayout 实现标签页切换
  • Android用户鉴权实现方案深度分析
  • react18更新哪些东西
  • Nginx和Apache的区别
  • Apache PDFBox深入实践
  • Apache JMeter 使用记录踩坑
  • MCP客户端架构与实施
  • Apache POI 介绍与使用指南
  • apache-doris安装兼datax-web配置