网站首页 > 开源技术 正文
上节引入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;
- 上一篇: 21.零基础开发商城项目:商品管理(后端)
- 下一篇: 程序员来到头条号的第一天(今日头条程序员)
猜你喜欢
- 2024-09-08 Try catch 太烦人了?只需一步一次搞定 Exception
- 2024-09-08 vue多实体参数怎么传?(vue如何传参)
- 2024-09-08 Mybatis-Plus常用的查询方法——看这一篇就够了!「图文例子」
- 2024-09-08 你这代码写得真丑,满屏的try-catch,全局异常处理不会吗?下
- 2024-09-08 mybatis-plus 团队新作 mybatis-mate 轻松搞定企业级数据处理
- 2024-09-08 「Spring Cloud」新闻头条微服务项目:自媒体文章管理
- 2024-09-08 最快MyBatis-Plus入门使用(mybatis-plus-plus)
- 2024-09-08 再也不用写CURD代码了,Mybatis-plus帮你全搞定
- 2024-09-08 MyBatis-Plus快速入门(一)(mybatis-plus-plus)
- 2024-09-08 Mybatis-Plus 详解(二)(mybatisplus in)
你 发表评论:
欢迎- 07-10公司网站建站选择:人工建站和源码建站分析
- 07-10多用途游戏娱乐新闻网站HTML5模板
- 07-10站长教你搭建属于自己的网站(搭建网站的步骤)
- 07-10php宝塔搭建部署实战响应式塑料封条制品企业网站模板源码
- 07-10自适应响应式汽车配件类网站源码 html5高端大气汽车网站织梦模板
- 07-10网站标签怎么设置?(网站标签怎么设置比较好)
- 07-10PageAdmin企业网站制作中踩过的坑
- 07-10豆包给我输出的html在线象棋源码(有点简单)
- 最近发表
- 标签列表
-
- jdk (81)
- putty (66)
- rufus (78)
- 内网穿透 (89)
- okhttp (70)
- powertoys (74)
- windowsterminal (81)
- netcat (65)
- ghostscript (65)
- veracrypt (65)
- asp.netcore (70)
- wrk (67)
- aspose.words (80)
- itk (80)
- ajaxfileupload.js (66)
- sqlhelper (67)
- express.js (67)
- phpmailer (67)
- xjar (70)
- redisclient (78)
- wakeonlan (66)
- tinygo (85)
- startbbs (72)
- webftp (82)
- vsvim (79)
本文暂时没有评论,来添加一个吧(●'◡'●)