mybatis-plus ---2
mybatis-plus插件
官网地址
分页插件
- MyBatis Plus自带分页插件,只要简单的配置即可实现分页功能
配置并使用自带分页插件
@Configuration
@MapperScan("com.itzhh.mapper")//可以将主类中的注解移到此处
public class MybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor(){MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}
}
@Testpublic void testPage(){//设置分页参数Page<User> page = new Page<>(2, 3);//Preparing: SELECT uid AS id,username AS name,//age,email,is_deleted FROM t_user WHERE is_deleted=0 LIMIT ?,?userMapper.selectPage(page,null);//获取分页数据List<User> list = page.getRecords();list.forEach(System.out::println);System.out.println();System.out.println("当前页:"+page.getCurrent());System.out.println("每页显示的条数:"+page.getSize());System.out.println("总记录数:"+page.getTotal());System.out.println("总页数:"+page.getPages());System.out.println("是否有上一页:"+page.hasPrevious());System.out.println("是否有下一页:"+page.hasNext());}
使用自定义分页插件
- 创建接口(注意,第一个参数一定要是Page)
@Repository
public interface UserMapper extends BaseMapper<User> {Page<User> selectPageVo(@Param("page")Page<User> page,@Param("age")Integer age);
}
- UserMapper.xml中编写SQL
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itzhh.mapper.UserMapper"><sql id="BaseColumns" >uid,username,age,email</sql><select id="selectPageVo" resultType="com.itzhh.pojo.User">select <include refid="BaseColumns"></include>from t_user where age>#{age}</select>
</mapper>
- 测试
@Testpublic void testSelectPageVo(){//设置分页参数Page<User> page = new Page<>(1, 2);userMapper.selectPageVo(page, 20);//获取分页数据List<User> list = page.getRecords();list.forEach(System.out::println);System.out.println("当前页:"+page.getCurrent());System.out.println("每页显示的条数:"+page.getSize());System.out.println("总记录数:"+page.getTotal());System.out.println("总页数:"+page.getPages());System.out.println("是否有上一页:"+page.hasPrevious());System.out.println("是否有下一页:"+page.hasNext());}
Mybatis-Plus实现乐观锁
- 添加version字段
- 添加乐观锁插件配置
@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor(){MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();//添加分页插件interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//添加乐观锁配置interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());return interceptor;}
- 测试
@Testpublic void testConcurrentVersionUpdate() {//小李取数据Product p1 = productMapper.selectById(00000000000000000001L);//小王取数据Product p2 = productMapper.selectById(00000000000000000001L);//小李修改 + 50p1.setPrice(p1.getPrice() + 50);int result1 = productMapper.updateById(p1);System.out.println("小李修改的结果:" + result1);//小王修改 - 30p2.setPrice(p2.getPrice() - 30);int result2 = productMapper.updateById(p2);System.out.println("小王修改的结果:" + result2);if(result2 == 0){//失败重试,重新获取version并更新p2 = productMapper.selectById(00000000000000000001L);p2.setPrice(p2.getPrice() - 30);result2 = productMapper.updateById(p2);}System.out.println("小王修改重试的结果:" + result2);//老板看价格Product p3 = productMapper.selectById(00000000000000000001L);System.out.println("老板看价格:" + p3.getPrice());}
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@15dc339f] was not registered for synchronization because synchronization is not active
2023-02-14 09:42:36.662 INFO 21336 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2023-02-14 09:42:36.842 INFO 21336 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@695085082 wrapping com.mysql.cj.jdbc.ConnectionImpl@59cda16e] will not be managed by Spring
==> Preparing: SELECT id,name,price,version FROM t_product WHERE id=?
==> Parameters: 1(Long)
<== Columns: id, name, price, version
<== Row: 1, 新华字典, 100, 1
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@15dc339f]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@10b1a751] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1406114969 wrapping com.mysql.cj.jdbc.ConnectionImpl@59cda16e] will not be managed by Spring
==> Preparing: SELECT id,name,price,version FROM t_product WHERE id=?
==> Parameters: 1(Long)
<== Columns: id, name, price, version
<== Row: 1, 新华字典, 100, 1
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@10b1a751]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5a1c3cb4] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@709841971 wrapping com.mysql.cj.jdbc.ConnectionImpl@59cda16e] will not be managed by Spring
==> Preparing: UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?
==> Parameters: 新华字典(String), 150(Integer), 2(Integer), 1(Long), 1(Integer)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5a1c3cb4]
小李修改的结果:1
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7f5538a1] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1929218620 wrapping com.mysql.cj.jdbc.ConnectionImpl@59cda16e] will not be managed by Spring
==> Preparing: UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?
==> Parameters: 新华字典(String), 70(Integer), 2(Integer), 1(Long), 1(Integer)
<== Updates: 0
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7f5538a1]
小王修改的结果:0
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@34780cd9] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1648278215 wrapping com.mysql.cj.jdbc.ConnectionImpl@59cda16e] will not be managed by Spring
==> Preparing: SELECT id,name,price,version FROM t_product WHERE id=?
==> Parameters: 1(Long)
<== Columns: id, name, price, version
<== Row: 1, 新华字典, 150, 2
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@34780cd9]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1ab5f08a] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1860118977 wrapping com.mysql.cj.jdbc.ConnectionImpl@59cda16e] will not be managed by Spring
==> Preparing: UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?
==> Parameters: 新华字典(String), 120(Integer), 3(Integer), 1(Long), 2(Integer)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1ab5f08a]
小王修改重试的结果:1
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66b59b7d] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1395725953 wrapping com.mysql.cj.jdbc.ConnectionImpl@59cda16e] will not be managed by Spring
==> Preparing: SELECT id,name,price,version FROM t_product WHERE id=?
==> Parameters: 1(Long)
<== Columns: id, name, price, version
<== Row: 1, 新华字典, 120, 3
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66b59b7d]
老板看价格:120
通用枚举
- 表中的有些字段值是固定的,例如性别(男或女),此时我们可以使用MyBatis-Plus的通用枚举来实现
- 创建枚举类(如果不加 @EnumValue,会报如下错误)
package com.itzhh.enums;import com.baomidou.mybatisplus.annotation.EnumValue;
import lombok.Getter;/*** Author: zhh* Date: 2023-02-14 10:11* Description: <描述>*/
@Getter
public enum SexEnum {MALE(1,"男"),FEMALE(0,"女");@EnumValueprivate Integer sex;private String sexName;SexEnum(Integer sex, String sexName) {this.sex = sex;this.sexName = sexName;}
}
- 添加枚举字段
- 配置扫描通用枚举
# 配置mybatis日志
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImplglobal-config:db-config:# 配置MyBatis-Plus操作表的默认前缀table-prefix: t_#配置mybatis-plus的主键策略id-type: auto# 配置扫描通用枚举type-enums-package: com.itzhh.enums
- 测试
@Testpublic void testSexEnum(){User user = new User();user.setName("Enum");user.setAge(20);//设置性别信息为枚举项,会将@EnumValue注解所标识的属性值存储到数据库user.setSex(SexEnum.MALE);userMapper.insert(user);}
代码生成器
- 引入依赖
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.5.1</version></dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.31</version></dependency>
@Testvoid contextLoads() {FastAutoGenerator.create("jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false", "root", "123456").globalConfig(builder -> {builder.author("zhh") // 设置作者//.enableSwagger() // 开启 swagger 模式.fileOverride() // 覆盖已生成文件.outputDir("E:\\IDEA\\IDEAProjects\\mybatis_plus_auto"); // 指定输出目录}).packageConfig(builder -> {builder.parent("com.itzhh") // 设置父包名.moduleName("mybatisplus") // 设置父包模块名.pathInfo(Collections.singletonMap(OutputFile.mapperXml, "E:\\IDEA\\IDEAProjects\\mybatis_plus_auto"));// 设置mapperXml生成路径}).strategyConfig(builder -> {builder.addInclude("t_user") // 设置需要生成的表名.addTablePrefix("t_", "c_"); // 设置过滤表前缀}).templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker 引擎模板,默认的是Velocity引擎模板.execute();}
多数据源
- 模拟场景
我们创建两个库,分别为:mybatis_plus(以前的库不动)与mybatis_plus_1(新建),将mybatis_plus库的product表移动到mybatis_plus_1库,这样每个库一张表,通过一个测试用例分别获取用户数据与商品数据,如果获取到说明多库模拟成功 - 添加依赖
<dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>3.5.0</version></dependency>
- 配置多数据源
spring:datasource:dynamic:strict: falsedatasource:master:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=falseusername: rootpassword: 123456slave_1:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/mybatis_plus_1?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=falseusername: rootpassword: 123456
# 配置mybatis日志
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
- 创建用户service
public interface UserService extends IService<User> {
}
@DS("master") //指定所操作的数据源
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
- 创建商品service
public interface ProductService extends IService<Product> {
}
@DS("slave_1") //指定所操作的数据源
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
}
- 测试
@Autowiredprivate UserService userService;@Autowiredprivate ProductService productService;@Testvoid contextLoads() {System.out.println(userService.getById(1L));System.out.println(productService.getById(1L));}
安装MybatisX插件并使用其简化开发
- 这个我一直再用,就不记录了
相关文章:

mybatis-plus ---2
mybatis-plus插件 官网地址 分页插件 MyBatis Plus自带分页插件,只要简单的配置即可实现分页功能 配置并使用自带分页插件 Configuration MapperScan("com.itzhh.mapper")//可以将主类中的注解移到此处 public class MybatisPlusConfig {Beanpublic …...

如何在Qt中设置背景图片,且不覆盖其它控件
正常情况,我们直接通过在样式表里设置背景图片会出现背景图片覆盖其它控件的情况,比如下面操作: 首先右击空白处,点击改变样式表。 然后选择background-image 然后点击铅笔图标 之后我们要先添加前缀,也就是我们…...
PMP考前冲刺2.14 | 2023新征程,一举拿证
承载2023新一年的好运让我们迈向PMP终点一起冲刺!一起拿证!每日5道PMP习题助大家上岸PMP!!!PMP项目管理题目1-2:1.公司了解到一个项目机会,领导让之前做过类似项目的项目经理报告一个粗略的成本…...

feign进行文件上传报错解决方案及有多个入参时的注意事项
一、情景回顾1、简单的文件上传的接口/*** 文件上传MultipartFile格式** param multipartFile 源文件* param filename 自定义文件名称,允许为空,为空时直接从源文件中拿* return*/RequestMapping("/uploadFileForMultipartFile")LogModuleAnn…...
java 枚举类型enum的用法详解
Java Enum原理 public enum Size{ SMALL, MEDIUM, LARGE, EXTRA_LARGE }; 实际上,这个声明定义的类型是一个类,它刚好有四个实例,在此尽量不要构造新对象。 因此,在比较两个枚举类型的值时,永远不需要调用equals方法…...

Java 基础面试题——关键字
目录1.Java 中的关键字是指什么?有哪些关键字?2.instanceof 关键字的作用是什么?3.访问修饰符 public、private、protected、以及不写(default)时的区别?4.Java 中有没有 goto 关键字?5.在 Java 中&#x…...

C++——运算符重载
1、运算符重载的概念 运算符重载,就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。运算符重载的目的是让语法更加简洁运算符重载不能改变本来寓意,不能改变基础类型寓意运算符重载的本质是另一种函数调用…...

前端食堂技术周刊第 70 期:Volar 的新开端、Lighthouse 10、良好的组件设计、React 纪录片、2022 大前端总结
美味值:🌟🌟🌟🌟🌟 口味:黑巧克力 食堂技术周刊仓库地址:https://github.com/Geekhyt/weekly 本期摘要 Volar 的新开端Chrome 110 的新功能Lighthouse 10Nuxt v3.2.0加速 JavaSc…...

react路由详解
在学习react路由之前,我们肯定需要安装路由。大家先运行如下命令安装路由。安装之后随我一起探索react路由。 安装 版本v6 npm i react-router-dom -S 页面准备 创建两个文件夹 pages和 router pages文件夹里面放的是页面 router文件夹里面是进行路由配置 路由…...

mysql数据库完全备份和增量备份与恢复
mysql数据备份: 数据备份方式 物理备份: 冷备:.冷备份指在数据库关闭后,进行备份,适用于所有模式的数据库热备:一般用于保证服务正常不间断运行,用两台机器作为服务机器,一台用于实际数据库操作应用,另外…...
CF1667E Centroid Probabilities
题目描述 对于所有点数为 nnn 的树,如果其满足 对于所有 i∈[2,n]i\in [2,n]i∈[2,n],与 iii 相连的 jjj 中有且只有一个点 jjj 满足 j<ij<ij<i ,那么我们称其为好树 对于 1∼n1\sim n1∼n 每个点求出来有多少好树满足重心为 iii …...

全网详细总结com.alibaba.fastjson.JSONException: syntax error, position at xxx常见错误方式
文章目录1. 复现问题2. 分析问题3. 解决问题4. 该错误的其他解决方法5. 重要补充1. 复现问题 今天在JSONObject.parse(json)这个方法时,却报出如下错误: com.alibaba.fastjson.JSONException: syntax error, position at 0, name usernameat com.aliba…...

快速部署个人导航页:美好的一天从井然有序开始
很多人都习惯使用浏览器自带的收藏夹来管理自己的书签,然而收藏夹存在着一些问题。 经过长时间的累积,一些高频使用的重要网站和偶尔信手收藏的链接混在了一起,收藏夹因为内容过多而显得杂乱无章;收藏夹没有什么美观可言…...
【Python】如何在 Python 中使用“柯里化”编写干净且可重用的代码
对于中级Python开发者来说,了解了Python的基础语法、库、方法,能够实现一些功能之后,进一步追求的就应该是写出优雅的代码了。 这里介绍一个很有趣的概念“柯里化”。 所谓柯里化(Currying)是把接受多个参数的函数变换…...

ROS笔记(4)——发布者Publisher与订阅者Subscribe的编程实现
发布者 以小海龟的话题消息为例,编程实现发布者通过/turtle1/cmd_vel 话题向 turtlesim节点发送消息,流程如图 步骤一 创建功能包(工作空间为~/catkin_ws/src) $ cd ~/catkin_ws/src $ catkin_create_pkg learning_topic roscpp rospy s…...

Linux进程概念(一)
文章目录Linux进程概念(一)1. 冯诺依曼体系结构2. 操作系统(Operator System)2.1 考虑2.2 如何理解操作系统对硬件做管理?2.3 操作系统为什么要对软硬件资源做管理呢?2.4 系统调用和库函数概念2.5 计算机体系结构3. 进程的初步理解…...

Leetcode.1124 表现良好的最长时间段
题目链接 Leetcode.1124 表现良好的最长时间段 Rating : 1908 题目描述 我们认为当员工一天中的工作小时数大于 8 小时的时候,那么这一天就是「劳累的一天」。 所谓「表现良好的时间段」,意味在这段时间内,「劳累的天数」是严格…...
达梦数据库会话、事务阻塞排查步骤
查询阻塞的事务IDselect * from v$trxwait order by wait_time desc;--单机select * from v$dsc_trxwait order by wait_time desc;–DSC集群查询阻塞事务的会话信息select sf_get_session_sql(sess_id),* from v$sessions where trx_id69667;--单机select sf_get_session_sql(…...

sqlServer 2019 开发版(Developer)下载及安装
下载软件 官网只有2022的,2019使用百度网盘进行下载 安装下崽器 选择自定义安装 选择语言、以及安装位置 点击“安装” 安装 SQL Server 可能的故障 以上步骤安装后会弹出以上界面,如果未弹出,手动去安装目录下点击 SETUP.EXE 文件…...

使用Arthas定位问题
功能概述 首先,Arthas的常用功能大概有以下几个: 解决依赖冲突 sc命令:模糊查看当前 JVM 中是否加载了包含关键字的类,以及获取其完全名称。 sc -d 关键字 注意使用 sc -d 命令,获取 classLoaderHash命令:…...

XCTF-web-easyupload
试了试php,php7,pht,phtml等,都没有用 尝试.user.ini 抓包修改将.user.ini修改为jpg图片 在上传一个123.jpg 用蚁剑连接,得到flag...

51c自动驾驶~合集58
我自己的原文哦~ https://blog.51cto.com/whaosoft/13967107 #CCA-Attention 全局池化局部保留,CCA-Attention为LLM长文本建模带来突破性进展 琶洲实验室、华南理工大学联合推出关键上下文感知注意力机制(CCA-Attention),…...

基于距离变化能量开销动态调整的WSN低功耗拓扑控制开销算法matlab仿真
目录 1.程序功能描述 2.测试软件版本以及运行结果展示 3.核心程序 4.算法仿真参数 5.算法理论概述 6.参考文献 7.完整程序 1.程序功能描述 通过动态调整节点通信的能量开销,平衡网络负载,延长WSN生命周期。具体通过建立基于距离的能量消耗模型&am…...
前端倒计时误差!
提示:记录工作中遇到的需求及解决办法 文章目录 前言一、误差从何而来?二、五大解决方案1. 动态校准法(基础版)2. Web Worker 计时3. 服务器时间同步4. Performance API 高精度计时5. 页面可见性API优化三、生产环境最佳实践四、终极解决方案架构前言 前几天听说公司某个项…...
Go 语言接口详解
Go 语言接口详解 核心概念 接口定义 在 Go 语言中,接口是一种抽象类型,它定义了一组方法的集合: // 定义接口 type Shape interface {Area() float64Perimeter() float64 } 接口实现 Go 接口的实现是隐式的: // 矩形结构体…...

为什么需要建设工程项目管理?工程项目管理有哪些亮点功能?
在建筑行业,项目管理的重要性不言而喻。随着工程规模的扩大、技术复杂度的提升,传统的管理模式已经难以满足现代工程的需求。过去,许多企业依赖手工记录、口头沟通和分散的信息管理,导致效率低下、成本失控、风险频发。例如&#…...

【第二十一章 SDIO接口(SDIO)】
第二十一章 SDIO接口 目录 第二十一章 SDIO接口(SDIO) 1 SDIO 主要功能 2 SDIO 总线拓扑 3 SDIO 功能描述 3.1 SDIO 适配器 3.2 SDIOAHB 接口 4 卡功能描述 4.1 卡识别模式 4.2 卡复位 4.3 操作电压范围确认 4.4 卡识别过程 4.5 写数据块 4.6 读数据块 4.7 数据流…...

QT: `long long` 类型转换为 `QString` 2025.6.5
在 Qt 中,将 long long 类型转换为 QString 可以通过以下两种常用方法实现: 方法 1:使用 QString::number() 直接调用 QString 的静态方法 number(),将数值转换为字符串: long long value 1234567890123456789LL; …...

使用 SymPy 进行向量和矩阵的高级操作
在科学计算和工程领域,向量和矩阵操作是解决问题的核心技能之一。Python 的 SymPy 库提供了强大的符号计算功能,能够高效地处理向量和矩阵的各种操作。本文将深入探讨如何使用 SymPy 进行向量和矩阵的创建、合并以及维度拓展等操作,并通过具体…...

Golang——9、反射和文件操作
反射和文件操作 1、反射1.1、reflect.TypeOf()获取任意值的类型对象1.2、reflect.ValueOf()1.3、结构体反射 2、文件操作2.1、os.Open()打开文件2.2、方式一:使用Read()读取文件2.3、方式二:bufio读取文件2.4、方式三:os.ReadFile读取2.5、写…...