springBoot-baomidou(苞米豆)用法具体实践
ztj100 2024-10-28 21:13 74 浏览 0 评论
上节引入baomidou后,只是做了简单的插入查询操作,这里准备多手敲一些具体例子,加深下印象。
参考例子 还是根据官网使用手册:https://baomidou.com/pages/24112f/
以下分为几部分:
一、条件构造器
二、查询操作
三、新增、更新、删除操作
四、分页插件(mybatisPlus内置方式)
数据准备下,还是之前的user、user_info表,(sql文末已附)
一、条件构造器:
// 单条查询执行
QueryWrapper<User> qw = new QueryWrapper<>();
qw.eq("user_name","dog2”); // eq 精确匹配
User u = userService.getOne(qw);
System.out.println("根据 字段值 查询:" + JSONObject.toJSONString(u.getUserName()));
// 其他条件构造例子
qw.ne("user_name","dog2"); // user_name <> 'dog2'
qw.gt("id",3); // id > 3
qw.ge("id", 3); // id >= 3
qw.lt("id", 3); // id < 3
qw.le("id", 3); // id <= 3
qw.between("id", 3,5); // id between 3 and 5
qw.notBetween("id", 3,5); // id not between 3 and 5
qw.isNull("phone"); // phone is null
qw.isNotNull("phone"); // phone is not null
// like 用法
qw.like("user_name","g"); // 全模糊匹配 user_name like '%g%'
qw.notLike("user_name", "g"); // user_name not like '%g%'
qw.likeLeft("user_name","2"); // 左模糊匹配 user_name like '%2'
qw.likeRight("user_name","d"); // 右模糊匹配 user_name like 'd%'
// 范围内查询 in
qw = new QueryWrapper<>();
qw.in("id", 3,2); // id in (3,2)
qw.notIn("id", 3,2); // id not in (3,2)
// inSql
qw.inSql("id", "2,3,4"); // id in (2,3,4)
qw.notInSql("id", "2,3,4"); // id in (2,3,4)
// id in (select user_id from user_info)
qw.inSql("id", "select user_id from user_info");
// id not in (xxxx)
qw.notInSql("id", "select user_id from user_info");
// groupBy
qw.groupBy("user_name","phone"); // group by user_name, phone
// orderByAsc
qw.orderByAsc("phone"); // order by phone asc
qw.orderByDesc("phone","user_name"); // order by phone desc, user_name desc
// and 嵌套
qw = new QueryWrapper<>();
// id between 1 and 5 and (user_name like '%dog%' and id <> 2)
qw.between("id",1,5);
qw.and(i -> i.like("user_name","dog").ne("id",2));
System.out.println(JSONObject.toJSONString(userService.list(qw).size()));
// or 嵌套
qw = new QueryWrapper<>();
// id between 1 and 5 or (user_name like '%dog%' and id <> 2)
qw.between("id",1,5);
qw.or(i -> i.like("user_name","dog").ne("id",2));
// 查询返回特定字段: id, user_name
qw.select("id","user_name");
二、查询操作:
参考 https://baomidou.com/pages/49cc81/
以下查询基于 条件构造器QueryWrapper
Get 查询:
Case1: 查询1条记录
qw = new QueryWrapper<>();
qw.in("id", 3,2); // id in (3,2)
// u = userService.getOne(qw); // 查询到多条返回数据的话,这里会抛错
// qw.last("limit 1"); // 或者末尾拼接查询 限制1条
u = userService.getOne(qw, false); // 设置false的话,多条返回时不会抛错
System.out.println("查询多条记录 返回1条:id=" + u.getId();
测试类执行:
Case2: 查询返回一个map对象
qw = new QueryWrapper<>();
qw.in("id", 3,2); // id in (3,2)
u = userService.getOne(qw, false); // 设置false的话,多条返回时不会抛错
System.out.println("查询多条记录 返回 map:" + JSONObject.toJSONString(userService.getMap(qw)));
执行testCase:这里有2条数据,但只会返回第一条map对象
List查询: https://baomidou.com/pages/49cc81/#list
Case1: 查询list
qw = new QueryWrapper<>();
qw.inSql("id", "select user_id from user_info"); // id in (select user_id from user_info)
System.out.println(userService.list(qw).size());
执行testCase:返回list数量为2
Case2: 根据map查询list
Map<String, Object> queryMap = new HashMap<>();
queryMap.put("id", 2);
List<User> list = userService.listByMap(queryMap);
System.out.println(JSONObject.toJSONString(list));
执行testCase:返回list 1条
Case3: 根据条件查询 mapList
qw = new QueryWrapper<>();
qw.inSql("id", "select user_id from user_info");
List<Map<String, Object>> mapList = userService.listMaps(qw);
System.out.println(JSONObject.toJSONString(mapList));
执行testCase:返回list 2条
Case4: count查询
long total = userService.count(); // 获取总条数
System.out.println(total);
long conditionTotal = userService.count(qw); // 根据查询条件获取 条数count
System.out.println(conditionTotal);
执行testCase:返回条数 5 , 2
三、DML操作:
1 新增操作
case1:单条insert
// 基于 id为2的记录,新增单条记录
User u = userService.getById(2);
u.setAvatarUrl("1");
u.setId(null);
userService.save(u); // 相当于sql的 insert操作
执行testCase:
case2: 批量insert
// 基于 id=3,id=4的2条记录,批量新增
List<Long> idList = Arrays.asList(3L,4L);
List<User> list = userService.listByIds(idList);
list.stream().forEach(o-> o.setId(null));
userService.saveBatch(list);
执行testCase:db新增 8、9
Case3: 批量insert 根据分页,这个很方便:)
List<Long> idList = Arrays.asList(4L,5L,6L);
List<User> list = userService.listByIds(idList);
list.stream().forEach(o-> o.setId(null));
userService.saveBatch(list,2); // 2条一分页 批量插入
执行testCase:db分2次执行了记录
Case4: saveOrUpdate用法
// TableId 注解存在更新记录,否插入一条记录
boolean saveOrUpdate(T entity);
// 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList);
// 批量修改插入,分批执行
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);
注解参考:参数bean中 id值在db中存在就更新,否则insert
2 更新操作:
// 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
boolean update(Wrapper<T> updateWrapper);
// 根据 whereWrapper 条件,更新记录
boolean update(T updateEntity, Wrapper<T> whereWrapper);
// 根据 ID 选择修改
boolean updateById(T entity);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList, int batchSize);
Case1: 根据ID更新
//实体类
User user = new User();
user.setUserId(1);
user.setAge(18);
userMapper.updateById(user);
Case2: 根据条件构造器作为参数 进行更新
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("user_name","dog2");
User user = new User();
user.setUserAccount("dog2Account");
user.setUpdateTime(LocalDateTime.now());
userService.update(user, updateWrapper);
3 删除操作:
// 根据 entity 条件,删除记录
boolean remove(Wrapper<T> queryWrapper);
// 根据 ID 删除
boolean removeById(Serializable id);
// 根据 columnMap 条件,删除记录
boolean removeByMap(Map<String, Object> columnMap);
// 删除(根据ID 批量删除)
boolean removeByIds(Collection<? extends Serializable> idList);
四、分页插件
1 使用mybatisPlus内置方式 实现分页
新增一个拦截器
package com.joy.demo.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
//@MapperScan("com.joy.demo.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 添加分页插件
PaginationInnerInterceptor pageInterceptor = new PaginationInnerInterceptor();
// 设置请求的页面大于最大页后操作,true调回到首页,false继续请求。默认false
pageInterceptor.setOverflow(false);
// 单页分页条数限制,默认无限制
pageInterceptor.setMaxLimit(500L);
// 设置数据库类型
pageInterceptor.setDbType(DbType.MYSQL);
interceptor.addInnerInterceptor(pageInterceptor);
return interceptor;
}
}
参考官方:
// 无条件分页查询
IPage<T> page(IPage<T> page);
// 条件分页查询
IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper);
// 无条件分页查询
IPage<Map<String, Object>> pageMaps(IPage<T> page);
// 条件分页查询
IPage<Map<String, Object>> pageMaps(IPage<T> page, Wrapper<T> queryWrapper);
测试类:
System.out.println("----- selectPage method test ------");
//分页参数
Page<User> page = Page.of(1,2); // 每页2条,当前查找第一页
//queryWrapper组装查询where条件
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getUserName,"dog4");
userService.page(page,queryWrapper);
page.getRecords().forEach(System.out::println);
执行结果:
DB中数据:分页查询出 4、9 两条记录
以下脚本,需要的取哈
CREATE TABLE `user` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id',
`user_name` varchar(256) DEFAULT NULL COMMENT '用户昵称',
`user_account` varchar(256) DEFAULT NULL COMMENT '账号',
`avatar_url` varchar(1024) DEFAULT NULL COMMENT '用户头像',
`gender` tinyint DEFAULT NULL COMMENT '性别',
`user_password` varchar(512) NOT NULL COMMENT '密码',
`phone` varchar(128) DEFAULT NULL COMMENT '电话',
`email` varchar(512) DEFAULT NULL COMMENT '邮箱',
`user_status` int NOT NULL DEFAULT '0' COMMENT '状态 0 - 正常',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`delete_flag` tinyint NOT NULL DEFAULT '0' COMMENT '是否删除',
`user_role` int NOT NULL DEFAULT '0' COMMENT '用户角色 0 - 普通用户 1 - 管理员',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='用户';
BEGIN;
INSERT INTO `user` (`id`, `user_name`, `user_account`, `avatar_url`, `gender`, `user_password`, `phone`, `email`, `user_status`, `create_time`, `update_time`, `delete_flag`, `user_role`) VALUES (2, 'dog2', 'dog2Account', 'https://636f-codenav-8grj8px727565176-1256524210.tcb.qcloud.la/img/logo.png', 0, 'xxx', '123', '456', 0, '2022-10-28 23:42:06', '2022-10-30 08:34:35', 0, 0);
INSERT INTO `user` (`id`, `user_name`, `user_account`, `avatar_url`, `gender`, `user_password`, `phone`, `email`, `user_status`, `create_time`, `update_time`, `delete_flag`, `user_role`) VALUES (3, 'dog3', 'dog3Account', 'https://636f-codenav-8grj8px727565176-1256524210.tcb.qcloud.la/img/logo.png', 0, 'xxx', '123', '456', 0, '2022-10-29 19:23:56', '2022-10-30 08:34:47', 0, 0);
INSERT INTO `user` (`id`, `user_name`, `user_account`, `avatar_url`, `gender`, `user_password`, `phone`, `email`, `user_status`, `create_time`, `update_time`, `delete_flag`, `user_role`) VALUES (4, 'dog4', 'dog4Account', 'https://636f-codenav-8grj8px727565176-1256524210.tcb.qcloud.la/img/logo.png', 0, 'xxx', '123', '456', 0, '2022-10-29 19:32:37', '2022-10-30 08:34:54', 0, 0);
INSERT INTO `user` (`id`, `user_name`, `user_account`, `avatar_url`, `gender`, `user_password`, `phone`, `email`, `user_status`, `create_time`, `update_time`, `delete_flag`, `user_role`) VALUES (5, 'bigDog', 'bigDogAccount', '', 0, 'xxx', '', '456', 0, '2022-10-29 19:32:37', '2022-10-30 08:50:28', 0, 0);
INSERT INTO `user` (`id`, `user_name`, `user_account`, `avatar_url`, `gender`, `user_password`, `phone`, `email`, `user_status`, `create_time`, `update_time`, `delete_flag`, `user_role`) VALUES (6, 'smallDog', 'smallDogAccount', 'https://636f-codenav-8grj8px727565176-1256524210.tcb.qcloud.la/img/logo.png', 0, 'xxx', '123', '456', 0, '2022-10-29 19:32:37', '2022-10-30 08:34:54', 0, 0);
COMMIT;
CREATE TABLE `user_info` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id',
`user_id` bigint DEFAULT NULL COMMENT 'userId',
`real_name` varchar(100) DEFAULT NULL COMMENT '真实姓名',
`address` varchar(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='用户实名信息';
BEGIN;
INSERT INTO `user_info` (`id`, `user_id`, `real_name`, `address`) VALUES (1, 2, '22', NULL);
INSERT INTO `user_info` (`id`, `user_id`, `real_name`, `address`) VALUES (2, 3, '33', NULL);
COMMIT;
相关推荐
- sharding-jdbc实现`分库分表`与`读写分离`
-
一、前言本文将基于以下环境整合...
- 三分钟了解mysql中主键、外键、非空、唯一、默认约束是什么
-
在数据库中,数据表是数据库中最重要、最基本的操作对象,是数据存储的基本单位。数据表被定义为列的集合,数据在表中是按照行和列的格式来存储的。每一行代表一条唯一的记录,每一列代表记录中的一个域。...
- MySQL8行级锁_mysql如何加行级锁
-
MySQL8行级锁版本:8.0.34基本概念...
- mysql使用小技巧_mysql使用入门
-
1、MySQL中有许多很实用的函数,好好利用它们可以省去很多时间:group_concat()将取到的值用逗号连接,可以这么用:selectgroup_concat(distinctid)fr...
- MySQL/MariaDB中如何支持全部的Unicode?
-
永远不要在MySQL中使用utf8,并且始终使用utf8mb4。utf8mb4介绍MySQL/MariaDB中,utf8字符集并不是对Unicode的真正实现,即不是真正的UTF-8编码,因...
- 聊聊 MySQL Server 可执行注释,你懂了吗?
-
前言MySQLServer当前支持如下3种注释风格:...
- MySQL系列-源码编译安装(v5.7.34)
-
一、系统环境要求...
- MySQL的锁就锁住我啦!与腾讯大佬的技术交谈,是我小看它了
-
对酒当歌,人生几何!朝朝暮暮,唯有己脱。苦苦寻觅找工作之间,殊不知今日之事乃我心之痛,难道是我不配拥有工作嘛。自面试后他所谓的等待都过去一段时日,可惜在下京东上的小金库都要见低啦。每每想到不由心中一...
- MySQL字符问题_mysql中字符串的位置
-
中文写入乱码问题:我输入的中文编码是urf8的,建的库是urf8的,但是插入mysql总是乱码,一堆"???????????????????????"我用的是ibatis,终于找到原因了,我是这么解决...
- 深圳尚学堂:mysql基本sql语句大全(三)
-
数据开发-经典1.按姓氏笔画排序:Select*FromTableNameOrderByCustomerNameCollateChinese_PRC_Stroke_ci_as//从少...
- MySQL进行行级锁的?一会next-key锁,一会间隙锁,一会记录锁?
-
大家好,是不是很多人都对MySQL加行级锁的规则搞的迷迷糊糊,一会是next-key锁,一会是间隙锁,一会又是记录锁。坦白说,确实还挺复杂的,但是好在我找点了点规律,也知道如何如何用命令分析加...
- 一文讲清怎么利用Python Django实现Excel数据表的导入导出功能
-
摘要:Python作为一门简单易学且功能强大的编程语言,广受程序员、数据分析师和AI工程师的青睐。本文系统讲解了如何使用Python的Django框架结合openpyxl库实现Excel...
- 用DataX实现两个MySQL实例间的数据同步
-
DataXDataX使用Java实现。如果可以实现数据库实例之间准实时的...
- MySQL数据库知识_mysql数据库基础知识
-
MySQL是一种关系型数据库管理系统;那废话不多说,直接上自己以前学习整理文档:查看数据库命令:(1).查看存储过程状态:showprocedurestatus;(2).显示系统变量:show...
- 如何为MySQL中的JSON字段设置索引
-
背景MySQL在2015年中发布的5.7.8版本中首次引入了JSON数据类型。自此,它成了一种逃离严格列定义的方式,可以存储各种形状和大小的JSON文档,例如审计日志、配置信息、第三方数据包、用户自定...
你 发表评论:
欢迎- 一周热门
-
-
MySQL中这14个小玩意,让人眼前一亮!
-
旗舰机新标杆 OPPO Find X2系列正式发布 售价5499元起
-
【VueTorrent】一款吊炸天的qBittorrent主题,人人都可用
-
面试官:使用int类型做加减操作,是线程安全吗
-
C++编程知识:ToString()字符串转换你用正确了吗?
-
【Spring Boot】WebSocket 的 6 种集成方式
-
PyTorch 深度学习实战(26):多目标强化学习Multi-Objective RL
-
pytorch中的 scatter_()函数使用和详解
-
与 Java 17 相比,Java 21 究竟有多快?
-
基于TensorRT_LLM的大模型推理加速与OpenAI兼容服务优化
-
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)