MyBatisPlus的基本使用之QueryWrapper

QueryWrapper是MyBatis-Plus中的一个查询封装类,用于构建带有条件的查询语句。

1. QueryWrapper

使用普通的方式来设置查询条件,而不是使用Lambda表达式。

  • 一系列方法设置查询条件。手动指定数据库表的列名作为方法的参数
    • select 设置查询的字段
    • eq、ne、gt、ge、lt、le 设置等于、不等于、大于、大于等于、小于、小于等于。
    • orderBy 排序方式
    • last 自定义SQL语句

2.区别

  • LambdaQueryChainWrapper使用Lambda表达式来设置查询条件,更加直观和类型安全
  • -而QueryWrapper使用普通方式来设置查询条件,更加灵活和通用

3.代码示例

package com.example.demo.mybatisplus.service;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.zmybatisplus.entity.User;
import com.example.demo.zmybatisplus.mapper.UserMapper;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@SpringBootTest
public class UserTest {@Autowiredprivate UserMapper userMapper;//----------------------------------  查询 ---------------------------------------------------//简单查询@Testpublic void testSelect() {//所有List<User> userList = userMapper.selectList(null);userList.forEach(System.out::println);//多个List<User> userList2 = userMapper.selectBatchIds(Arrays.asList(1L,2L,3L));userList2.forEach(System.out::println);//单个User user3 = userMapper.selectById(1L);System.out.println(user3);}//等值条件查询,-- HashMap@Testpublic void testSelectByMap() {HashMap<String, Object> map = new HashMap<>();//定义查询条件map.put("name", "小垃圾"); //where k = vmap.put("age",0);List<User> users = userMapper.selectByMap(map);users.forEach(System.out::println);}//Wrapper查询---1.数字的比较 2.字符串的模糊查询@Testpublic void testSelectByWrapper() {//链式调用构造查询条件QueryWrapper<User> queryWrapper=new QueryWrapper<>();queryWrapper.isNotNull("name").like("email","john").le("age",26).lt("version",2).orderByAsc("id","age");//选择API执行queryList<User> users = userMapper.selectList(queryWrapper);users.forEach(System.out::println);//        eq相等   ne不相等,   gt大于,    lt小于         ge大于等于       le 小于等于//        equal/ not equal/ greater than/ less than/ less than or equal/ great than or equal///模糊查询 like  notLike  likeLeft(%x)  likeRight   notLikeLeft  notLikeRight}//Wrapper查询---1. 查询区间内的记录  between//              2.集合  in (in  notIn)(inSql   notInSql)@Testvoid test2SelectByWrapper(){//查询区间内的记录  betweenQueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.isNotNull("name").between("age",20,30);Long count = userMapper.selectCount(wrapper);System.out.println("count = " + count);//集合IN : in  notInQueryWrapper<User> queryWrapper=new QueryWrapper<>();queryWrapper.in("id",Arrays.asList(1L,2L,3L,4L));Long c=userMapper.selectCount(queryWrapper);System.out.println("count="+c);// 集合  IN ( sql语句 )  :  inSql   notInSql//例: inSql("age", "1,2,3,4,5,6")--->age in (1,2,3,4,5,6)//例: inSql("id", "select id from table where id < 3")--->id in (select id from table where id < 3)QueryWrapper<User> queryWrapper2=new QueryWrapper<>();//queryWrapper2.inSql("id","1,2,3,4");//两种写法queryWrapper2.inSql("id","select id from user where id<=4");Long c2=userMapper.selectCount(queryWrapper);System.out.println("count="+c2);}//Wrapper查询---分组查询 groupBy  having@Testpublic void testGroupByByWrapper(){QueryWrapper<User> wrapper=new QueryWrapper<>();wrapper.select("version","sum(age) as num").groupBy("version").having("sum(age)>0").orderByDesc("num");//使用Map获取返回结果List<Map<String,Object>> list=userMapper.selectMaps(wrapper);list.forEach(System.out::println);}//Wrapper更新---@Testpublic void testUpdateWrapper() {//修改--所有的记录//        //方式1
//        UpdateWrapper<User> updateWrapper=new UpdateWrapper<>();
//        updateWrapper.set("name","updateName").set("email",null);
//        userMapper.update(updateWrapper);
//
//        //方式2
//        String sql = "name = 'updateName1', email = null ";
//        int affectedRows = userMapper.update(new UpdateWrapper<User>().setSql(sql));
//        System.out.println("Affected rows: " + affectedRows);//修改 -- id=1的记录  UpdateWrapper拥有 QueryWrapper一样的条件方法UpdateWrapper<User> updateWrapper2 = new UpdateWrapper<>();updateWrapper2.set("name", "updateName111").set("email", "人文氛围v给xxx@123.cpm").eq("id", 1);userMapper.update(null, updateWrapper2);}//分页查询@Testpublic void testPage() {Page<User> page = new Page<>(2,5); //开启拦截器后,会注册一个page对象  当前页,每页条数//方法源码:   <P extends IPage<T>> P selectPage(P page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);userMapper.selectPage(page,null); //分页查询page.getRecords().forEach(System.out::println); //获取分页后的数据 打印System.out.println(page.getTotal()); //获取记录总数}//链式查询:  使用 Lambda 表达式的链式查询对象/*public List<User> getUserListByQueryWrapper() {QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.eq("age", 25).like("name", "John").orderByDesc("create_time");List<User> userList = userMapper.selectList(queryWrapper);return userList;}public List<User> getUserListByLambdaQueryChainWrapper() {LambdaQueryChainWrapper<User> lambdaQueryWrapper = new LambdaQueryChainWrapper<>(userMapper);lambdaQueryWrapper.eq(User::getAge, 25).like(User::getName, "John").orderByDesc(User::getCreateTime);List<User> userList = lambdaQueryWrapper.list();return userList;}public List<User> getUserListByLambdaQueryChainWrapperWithPage(int pageNum, int pageSize) {LambdaQueryChainWrapper<User> lambdaQueryWrapper = new LambdaQueryChainWrapper<>(userMapper);lambdaQueryWrapper.eq(User::getAge, 25).like(User::getName, "John").orderByDesc(User::getCreateTime).page(new Page<>(pageNum, pageSize));List<User> userList = lambdaQueryWrapper.list();return userList;}*///---------------------------增删改-查-------------------------------------------//加入了逻辑删除之后,查询会自动增加 delfalg=0;@Testpublic void testSelectById() {System.out.println("----- selectById method test -----");User user = userMapper.selectById(1L);Assertions.assertNotNull(user);System.out.println(user);}@Testpublic void testInsert() {System.out.println("----- insert method test -----");User user = new User();user.setName("John 雪花算法");user.setAge(25);user.setEmail("john.doe@example.com");int result = userMapper.insert(user);Assertions.assertEquals(1, result);System.out.println("Inserted user ID: " + user.getId());}@Testpublic void testUpdateById() {System.out.println("----- updateById method test -----");User user = new User();user.setId(1L);user.setAge(0);//update注解优先自定义设值int result = userMapper.updateById(user);Assertions.assertEquals(1, result);}//配置了全局逻辑删除 delfalg=0;@Testpublic void testDeleteById() {System.out.println("----- deleteById method test -----");int result = userMapper.deleteById(5L);Assertions.assertEquals(1, result);int r=userMapper.deleteBatchIds(Arrays.asList(1L,2L,3L));}//-------------------------- 乐观锁     ---------------------------------/*乐观锁(OptimisticLockerInnerInterceptor)机制:当要更新一条记录的时候,希望这条记录没有被别人更新乐观锁实现方式:
取出记录时,获取当前version
更新时,带上这个version
执行更新时, set version = newVersion where version = oldVersion
如果version不对,就更新失败*/@Test//乐观锁测试public void testOptimisticLocker(){//1、查询用户信息User user = userMapper.selectById(1L);//2、修改用户信息user.setEmail("123@qq.com");user.setName("小垃圾");//3、更新操作userMapper.updateById(user);  //WHERE id=? AND version=?}@Testpublic void testOptimisticLocker2(){//模拟多线程User user = userMapper.selectById(2L);user.setEmail("111jdw@qq.com");user.setName("帅小伙111");//我们在这里对线程1修改值//线程2插队User user2 = userMapper.selectById(2L);user2.setEmail("222jdw@qq.com");user2.setName("帅小伙222");userMapper.updateById(user2); //线程2抢先提交userMapper.updateById(user);//线程1失败,乐观锁在这种情况下防止了脏数据存在,没有乐观锁就会有覆盖掉线程2的操作}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/660824.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之TextClock组件

鸿蒙&#xff08;HarmonyOS&#xff09;项目方舟框架&#xff08;ArkUI&#xff09;之TextClock组件 一、操作环境 操作系统: Windows 10 专业版、IDE:DevEco Studio 3.1、SDK:HarmonyOS 3.1 二、TextClock组件 TextClock组件通过文本将当前系统时间显示在设备上。支持不同…

Linux 内核版本和发布历史

版本命名 在 2.6.x 版本以前&#xff0c;托瓦兹将核心的发展趋势分为两股&#xff0c;并根据这两股核心的发展分别给予不 同的核心编号。次版本为奇数表示发展中版本(development) 如2.5.xx&#xff0c;这种核心版本主要用在测试与测试新功能。次版本为偶数表示稳定版本 (stab…

Pytorch从零开始实战18

Pytorch从零开始实战——人脸图像生成 本系列来源于365天深度学习训练营 原作者K同学 文章目录 Pytorch从零开始实战——人脸图像生成环境准备模型定义开始训练可视化总结 环境准备 本文基于Jupyter notebook&#xff0c;使用Python3.8&#xff0c;Pytorch2.0.1cu118&#…

【2024年美赛即将开赛】最后一天如何提高获奖率

美赛思路预定 01 美赛赛中时间分配美赛时间安排比赛前2~3天第一天&#xff08;2号&#xff09;第二天&#xff08;3号&#xff09;第三天&#xff08;4号&#xff09;第四天&#xff08;5号&#xff09;第五天&#xff08;6号&#xff09;8&#xff1a;00~10&#xff1a;00 02 …

Hadoop-生产调优(更新中)

第1章 HDFS-核心参数 1.1 NameNode内存生产配置 1&#xff09;NameNode 内存计算 每个文件块大概占用 150 byte&#xff0c;一台服务器 128G 内存为例&#xff0c;能存储多少文件块呢&#xff1f; 128 * 1024 * 1024 * 1024 / 150byte ≈ 9.1 亿G MB KB Byte 2&#xff09…

前端构建变更:从 webpack 换 vite

现状 这里以一个 op &#xff08;内部运营管理用&#xff09;项目为例&#xff0c;从 webpack 构建改为 vite 构建&#xff0c;提高本地开发效率&#xff0c;顺便也加深对 webpack 、 vite 的了解。 vite 是前端构建工具&#xff0c;使用 一系列预配置进行rollup 打包&#x…

【SpringBoot】如何在 Utils 工具类中注入 Bean

一、背景 在 controller 层想使用一个静态工具&#xff0c;这个静态工具要使用其它组件。 我们经常要使用 Autowired 注解注入 Service 或者 Mapper 接口&#xff0c;在 service 层中注入其它的service 接口或者 mapper 接口都是可以的&#xff0c;但是如果我们要在我们自己封…

gdb 调试 - 在vscode图形化展示在远程的gdb debug过程

前言 本地机器的操作系统是windows&#xff0c;远程机器的操作系统是linux&#xff0c;开发在远程机器完成&#xff0c;本地只能通过ssh登录到远程。现在目的是要在本地进行图形化展示在远程的gdb debug过程。&#xff08;注意这并不是gdb remote &#xff01;&#xff01;&am…

【论文阅读笔记】Time Series Contrastive Learning with Information-Aware Augmentations

Time Series Contrastive Learning with Information-Aware Augmentations 摘要 背景&#xff1a;在近年来&#xff0c;已经有许多对比学习方法被提出&#xff0c;并在实证上取得了显著的成功。 尽管对比学习在图像和语言领域非常有效和普遍&#xff0c;但在时间序列数据上的应…

题目 1107: 纪念品分组

题目描述: 元旦快到了&#xff0c;校学生会让乐乐负责新年晚会的纪念品发放工作。为使得参加晚会的同学所获得 的纪念品价值相对均衡&#xff0c;他要把购来的纪念品根据价格进行分组&#xff0c;但每组最多只能包括两件纪念品&#xff0c; 并且每组纪念品的价格之和不能超过一…

Vue2中使用 el-dialog 对话框自行封装可拖动拖拽插件

文章目录 需求分析 需求 实现可拖拽的 el-dialog 分析 1.在utils文件创建dialogdrag.js文件&#xff0c;自定义指令 javascript复制代码//自定义指令&#xff1a;实现element-ui对话框dialog拖拽功能 import Vue from vue// v-dialogDrag: 弹窗拖拽 Vue.directive(dialogDr…

前端面试题-typeof 与instanceof区别(2024.2.1)

1、相同点以及概念 typeof 和 instanceof 都是 JavaScript 中用于检测值类型的运算符 2、typeof typeof 用于检测一个值的数据类型&#xff0c;返回的结果是一个字符串&#xff0c;表示被检测值的数据类型。常用的返回值有&#xff1a;"number", "string&quo…

实现vue3响应式系统核心-shallowReactive

简介 今天来实现一下 shallowReactive 这个 API。 reactive函数是一个深响应&#xff0c;当你取出的值为对象类型&#xff0c;需要再次调用 reactive进行响应式处理。很明显我们目前的代码是一个浅响应&#xff0c;即 只代理了对象的第一层&#xff0c;也就是 shallowReactiv…

36万的售价,蔚来理想卖得,小米卖不得?

文 | AUTO芯球 作者 | 雷歌 Are you OK&#xff1f;雷军被网友们叫“小雷”&#xff01; 被网友一猜再猜的小米SU7的价格&#xff0c;因为一份保险上牌价格单的曝光被网友吵得热热闹闹&#xff0c;曝出的小米汽车顶配上牌保险价格为36.14万。 20万以下&#xff0c;人们愿称…

BeanUtil.copyProperties(source,target)拷贝List注意事项

一&#xff1a;抛出问题 import cn.hutool.core.bean.BeanUtil; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.ArrayList; import java.util.List; Data AllArgsConstructor NoArgsConstructor public class Us…

【python】OpenCV—Tracking(10.1)

学习来自《Learning OpenCV 3 Computer Vision with Python》Second Edition by Joe Minichino and Joseph Howse 文章目录 检测移动的目标涉及到的 opencv 库cv2.GaussianBlurcv2.absdiffcv2.thresholdcv2.dilatecv2.getStructuringElementcv2.findContourscv2.contourAreacv2…

对比上次MySQL的DDL

MySQL的DDL未必都是可以快速完成的&#xff0c;那么Oracle同等场景下如何&#xff1f; 这个是在Oracle19C下的实验&#xff0c;特别说明。因为在Oracle11G下有些结论是不成立的。 表thousand有大约4000万行记录 SQL> set timing on; SQL> desc thousand; Name T…

css多行文本擦拭效果

<!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8" /><meta name"viewport" content"widthdevice-width, initial-scale1.0" /><title>多行文本擦拭效果</title><style>* …

C++编程||日期类,日期相减,实现日期的下一天 两个日期 相减 日期 + 天数 得到的日期

日期类&#xff0c;日期相减&#xff0c;实现日期的下一天 两个日期 相减 日期 天数 得到的日期 具体要求&#xff1a;实现类date,其中 构造函数包括year,month,day三个参数 重载两个date类…

亚信安全助力宁夏首个人工智能数据中心建成 铺设绿色算力安全底座

近日&#xff0c;由宁夏西云算力科技有限公司倾力打造&#xff0c;亚信安全科技股份有限公司&#xff08;股票代码&#xff1a;688225&#xff09;全力支撑&#xff0c;总投资达数十亿元人民币的宁夏智算中心项目&#xff0c;其一期工程——宁夏首个采用全自然风冷技术的30KW机…