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

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

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

相关推荐

Docker安全开放远程访问连接权限(docker 远程授权访问)

1、Docker完全开放远程访问Docker服务完全开放对外访问权限操作如下:#开启端口命令(--permanent永久生效,没有此参数重启后失效)firewall-cmd--zone=pu...

SpringCloud系列——4OpenFeign简介及应用

学习目标什么是OpenFeign以及它的作用RPC到底怎么理解OpenFeign的应用第1章OpenFeign简介在前面的内容中,我们分析了基于RestTemplate实现http远程通信的方法。并...

Spring Boot集成qwen:0.5b实现对话功能

1.什么是qwen:0.5b?模型介绍:Qwen1.5是阿里云推出的一系列大型语言模型。Qwen是阿里云推出的一系列基于Transformer的大型语言模型,在大量数据(包括网页文本、书籍、代码等)...

JDK从8升级到21的问题集(jdk8升级到11)

一、背景与挑战1.升级动因oOracle长期支持策略o现代特性需求:协程、模式匹配、ZGC等o安全性与性能的需求oAI新技术引入的版本要求...

大白话详解Spring Cloud服务降级与熔断

1.Hystrix断路器概述1.1分布式系统面临的问题复杂分布式体系结构中的应用程序有数十个依赖关系,每个依赖关系在某些时候将不可避免地失败。这就造成有可能会发生...

面试突击43:lock、tryLock、lockInterruptibly有什么区别?

在Lock接口中,获取锁的方法有4个:lock()、tryLock()、tryLock(long,TimeUnit)、lockInterruptibly(),为什么需要这么多方法?这些方法都有...

了解网络编程 TCP/IP 协议与UDP 协议

因为iP地址比较难记忆,很多情况下可以使用域名代替iP地址。1.TCP/IP协议与UDP协议通过IP地址与端口号确定计算机在网络中的位置后,接下来考虑通讯的问题:因为不同计算机的软硬件平台...

Semaphore与Exchanger的区别(semaphore和signal)

Semaphore和Exchanger是Java并发编程中两个常用的同步工具类,它们都可以用于协调多个线程之间的执行顺序和状态,但它们的作用和使用方式有所不同:Semaphore类表示一个...

Java教程:什么是分布式任务调度?怎样实现任务调度?

通常任务调度的程序是集成在应用中的,比如:优惠卷服务中包括了定时发放优惠卷的的调度程序,结算服务中包括了定期生成报表的任务调度程序...

java多线程—Runnable、Thread、Callable区别

多线程编程优点:进程之间不能共享内存,但线程之间共享内存非常容易。系统创建线程所分配的资源相对创建进程而言,代价非常小。Java中实现多线程有3种方法:继承Thread类实现Runnable...

工厂模式详解(工厂模式是啥意思)

工厂模式详解简单工厂简单工厂模式(SimpleFactoryPattern)是指由一个工厂对象决定创建出哪一种产品类的实例。简单工厂适用于工厂类负责创建的对象较少的场景,且客户端只需要传入工厂类的...

我们程序员眼中的母亲节(你眼中的程序员是什么样子的?程序员的薪酬如何?)

导语:对于我们成人来说,尤其是漂泊在外的程序员,陪伴父母的时间太少了。每逢佳节倍思亲,我们流浪外在的游子应该深有感触。母亲,是世界上最伟大的人,她承载着对我们的爱,更是负担和压力。我们作为子女,只会嫌...

死锁的 4 种排查工具(死锁检测方法要解决两个问题)

死锁(DeadLock)指的是两个或两个以上的运算单元(进程、线程或协程),都在等待对方停止执行,以取得系统资源,但是没有一方提前退出,就称为死锁。死锁示例接下来,我们先来演示一下Java中最简...

1. 工厂模式详解(工厂模式示例)

我们的项目代码也是由简而繁一步一步迭代而来的,但对于调用者来说却是越来越简单化。简单工厂模式简单工厂模式(SimpleFactoryPattern)是指由一个工厂对象决定创建出哪一种产品类的实例。...

Jmeter(二十):jmeter对图片验证码的处理

jmeter对图片验证码的处理在web端的登录接口经常会有图片验证码的输入,而且每次登录时图片验证码都是随机的;当通过jmeter做接口登录的时候要对图片验证码进行识别出图片中的字段,然后再登录接口中...

取消回复欢迎 发表评论: