springBoot-baomidou(苞米豆)用法具体实践
ztj100 2024-10-28 21:13 33 浏览 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;
相关推荐
- 再说圆的面积-蒙特卡洛(蒙特卡洛方法求圆周率的matlab程序)
-
在微积分-圆的面积和周长(1)介绍微积分方法求解圆的面积,本文使用蒙特卡洛方法求解圆面积。...
- python创建分类器小结(pytorch分类数据集创建)
-
简介:分类是指利用数据的特性将其分成若干类型的过程。监督学习分类器就是用带标记的训练数据建立一个模型,然后对未知数据进行分类。...
- matplotlib——绘制散点图(matplotlib散点图颜色和图例)
-
绘制散点图不同条件(维度)之间的内在关联关系观察数据的离散聚合程度...
- python实现实时绘制数据(python如何绘制)
-
方法一importmatplotlib.pyplotaspltimportnumpyasnpimporttimefrommathimport*plt.ion()#...
- 简单学Python——matplotlib库3——绘制散点图
-
前面我们学习了用matplotlib绘制折线图,今天我们学习绘制散点图。其实简单的散点图与折线图的语法基本相同,只是作图函数由plot()变成了scatter()。下面就绘制一个散点图:import...
- 数据分析-相关性分析可视化(相关性分析数据处理)
-
前面介绍了相关性分析的原理、流程和常用的皮尔逊相关系数和斯皮尔曼相关系数,具体可以参考...
- 免费Python机器学习课程一:线性回归算法
-
学习线性回归的概念并从头开始在python中开发完整的线性回归算法最基本的机器学习算法必须是具有单个变量的线性回归算法。如今,可用的高级机器学习算法,库和技术如此之多,以至于线性回归似乎并不重要。但是...
- 用Python进行机器学习(2)之逻辑回归
-
前面介绍了线性回归,本次介绍的是逻辑回归。逻辑回归虽然名字里面带有“回归”两个字,但是它是一种分类算法,通常用于解决二分类问题,比如某个邮件是否是广告邮件,比如某个评价是否为正向的评价。逻辑回归也可以...
- 【Python机器学习系列】拟合和回归傻傻分不清?一文带你彻底搞懂
-
一、拟合和回归的区别拟合...
- 推荐2个十分好用的pandas数据探索分析神器
-
作者:俊欣来源:关于数据分析与可视化...
- 向量数据库:解锁大模型记忆的关键!选型指南+实战案例全解析
-
本文较长,建议点赞收藏,以免遗失。更多AI大模型应用开发学习视频及资料,尽在...
- 用Python进行机器学习(11)-主成分分析PCA
-
我们在机器学习中有时候需要处理很多个参数,但是这些参数有时候彼此之间是有着各种关系的,这个时候我们就会想:是否可以找到一种方式来降低参数的个数呢?这就是今天我们要介绍的主成分分析,英文是Princip...
- 神经网络基础深度解析:从感知机到反向传播
-
本文较长,建议点赞收藏,以免遗失。更多AI大模型应用开发学习视频及资料,尽在...
- Python实现基于机器学习的RFM模型
-
CDA数据分析师出品作者:CDALevelⅠ持证人岗位:数据分析师行业:大数据...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- 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)