百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

springBoot-baomidou(苞米豆)用法具体实践

ztj100 2024-10-28 21:13 64 浏览 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;

相关推荐

Python 操作excel的坑__真实的行和列

大佬给的建议__如何快速处理excelopenpyxl库操作excel的时候,单个表的数据量大一些处理速度还能接受,如果涉及多个表甚至多个excel文件的时候速度会很慢,还是建议用pandas来处理,...

Python os.path模块使用指南:轻松处理文件路径

前言在Python编程中,文件和目录的操作是非常重要的一部分。为了方便用户进行文件和目录的操作,Python标准库提供了os模块。其中,os.path子模块提供了一些处理文件路径的函数和方法。本文主要...

Python常用内置模块介绍——文件与系统操作详解

Python提供了多个强大的内置模块用于文件和系统操作,下面我将详细介绍最常用的几个模块及其核心功能。1.os模块-操作系统交互...

Python Flask 建站框架实操教程(flask框架网页)

下面我将带您从零开始构建一个完整的Flask网站,包含用户认证、数据库操作和前端模板等核心功能。##第一部分:基础项目搭建###1.创建项目环境```bash...

为你的python程序上锁:软件序列号生成器

序列号很多同学可能开发了非常多的程序了,并且进行了...

PO设计模式全攻略,在 UI 自动化中的实践总结(以企业微信为例)

一、什么是PO设计模式?PO(PageObject)设计模式将某个页面的所有元素对象定位和对元素对象的操作封装成一个Page类,即一个py文件,并以页面为单位来写测试用例,实现页面对象和测试用例的...

这种小工具居然也能在某鱼卖钱?我用Python一天能写...

前两天在某鱼闲逛,本来想找个二手机械键盘,结果刷着刷着突然看到有人在卖——Word批量转PDF小工具...

python打包成exe,程序有图标,但是任务栏和窗口都没有显示图标

代码中指定图标信息#设置应用ID,确保任务栏图标正确显示ifsys.platform=="win32":importctypesapp_id=...

使用Python构建电影推荐系统(用python做推荐系统)

在日常数据挖掘工作中,除了会涉及到使用Python处理分类或预测任务,有时候还会涉及推荐系统相关任务。...

python爬取并分析淘宝商品信息(python爬取淘宝商品数据)

python爬取并分析淘宝商品信息背景介绍一、模拟登陆二、爬取商品信息1.定义相关参数2.分析并定义正则3.数据爬取三、简单数据分析1.导入库2.中文显示3.读取数据4.分析价格分布5.分析销售...

OpenCV入门学习基础教程(从小白变大神)

Opencv是用于快速处理图像处理、计算机视觉问题的工具,支持多种语言进行开发如c++、python、java等,下面这篇文章主要给大家介绍了关于openCV入门学习基础教程的相关资料,需要的朋友可以...

python图像处理-一行代码实现灰度图抠图

抠图是ps的最基本技能,利用python可以实现用一行代码实现灰度图抠图。基础算法是...

从头开始学python:如何用Matplotlib绘图表

Matplotlib是一个用于绘制图表的库。如果你有用过python处理数据,那Matplotlib可以更直观的帮你把数据展示出来。直接上代码看例子:importmatplotlib.pyplot...

Python爬取爱奇艺腾讯视频 250,000 条数据分析为什么李诞不值得了

在《Python爬取爱奇艺52432条数据分析谁才是《奇葩说》的焦点人物?》这篇文章中,我们从爱奇艺爬取了5万多条评论数据,并对一些关键数据进行了分析,由此总结出了一些明面上看不到的数据,并...

Python Matplotlib 库使用基本指南

简介Matplotlib是一个广泛使用的Python数据可视化库,它可以创建各种类型的图表、图形和可视化效果。无论是简单的折线图还是复杂的热力图,Matplotlib提供了丰富的功能来满足我们...

取消回复欢迎 发表评论: