EmmmuaCode EmmmuaCode
首页​
导航🚀​
  • 数据结构
  • 计算机网络
  • Java基础

    • JavaSE
    • JVM虚拟机
    • JUC并发编程
  • JavaWeb

    • Servlet
    • MVC
    • filter|listener
  • HTML
  • CSS
  • JavaScript
  • Vue
  • uni-app
  • Spring5
  • SpringMVC
  • SpringBoot2
  • SpringCloud
  • SpringSecurity
  • 搜索引擎

    • ElasticSearch
  • 消息队列

    • RabbitMQ
  • 服务器

    • Nginx🌐
  • 服务框架

    • Dubbo
  • Python基础
  • 数据分析
  • Hadoop
  • SQL 数据库

    • MySQL
  • NoSQL 数据库

    • NoSQL数据库概论
    • Redis
    • MongoDB
    • HBase
  • 框架

    • MyBatis
    • MyBatis-Plus
    • ShardingSphere
  • 部署

    • Linux
    • Docker
  • 管理

    • Maven
    • Git
  • 友情链接
  • 优秀博客文章
  • 索引

    • 分类
    • 标签
    • 归档
  • 其他

    • 关于
Github (opens new window)

wufan

海内存知己,天涯若比邻。
首页​
导航🚀​
  • 数据结构
  • 计算机网络
  • Java基础

    • JavaSE
    • JVM虚拟机
    • JUC并发编程
  • JavaWeb

    • Servlet
    • MVC
    • filter|listener
  • HTML
  • CSS
  • JavaScript
  • Vue
  • uni-app
  • Spring5
  • SpringMVC
  • SpringBoot2
  • SpringCloud
  • SpringSecurity
  • 搜索引擎

    • ElasticSearch
  • 消息队列

    • RabbitMQ
  • 服务器

    • Nginx🌐
  • 服务框架

    • Dubbo
  • Python基础
  • 数据分析
  • Hadoop
  • SQL 数据库

    • MySQL
  • NoSQL 数据库

    • NoSQL数据库概论
    • Redis
    • MongoDB
    • HBase
  • 框架

    • MyBatis
    • MyBatis-Plus
    • ShardingSphere
  • 部署

    • Linux
    • Docker
  • 管理

    • Maven
    • Git
  • 友情链接
  • 优秀博客文章
  • 索引

    • 分类
    • 标签
    • 归档
  • 其他

    • 关于
Github (opens new window)
  • MySQL-基础

    • MySQL-简介
    • MySQL-CRUD
    • MySQL-函数
    • MySQL 多表查询
    • MySQL 约束与自增长
    • MySQL 索引与事务
    • MySQL 表类型和存储引擎
    • MySQL 视图与管理
  • MySQL-进阶

    • MySQL 存储引擎
    • MySQL 索引
    • MySQL SQL优化
    • MySQL 视图/存储过程/触发器
    • MySQL 锁
    • MySQL InnoDB引擎
    • MySQL 管理
  • MySQL-运维

    • MySQL 日志
    • MySQL 主从复制
    • MySQL 分库分表
    • MySQL 读写分离
  • NoSQL 数据库概论

    • 非关系型数据库
    • NoSQL数据库理论基础
    • NoSQL数据库分类
  • Redis

    • Redis 数据库简介
    • Redis 概述安装
    • 常用五大数据类型
    • Redis 配置文件
    • Redis 发布和订阅
    • Redis 新数据类型
    • Redis Java整合
    • Redis 事务与锁
    • Redis 持久化操作
    • Redis 主从复制
    • Redis 集群搭建
    • Redis 缓存问题
    • Redis 分布式锁
    • Redisson 的应用
    • Redis 6.0新功能
  • MongoDB

    • MongoDB 相关概念
    • MongoDB 安装
    • MongoDB 常用命令
    • MongoDB 索引-Index
    • MongoDB 整合Java案例
    • MongoDB 集群和安全
  • HBase

    • HBase简介
    • HBase系统架构
    • HBase数据定义
    • HBase数据操作
    • HBase基本原理
  • MyBatis

    • MyBatis 入门案例
    • XML 配置
    • XML 映射文件
    • 动态SQL
    • 缓存
    • MyBatis的逆向工程
    • 分页插件
  • MyBatis-Plus

    • MyBatis-Plus 简介
    • MyBatis-Plus 入门案例
    • MyBatis-Plus 基本CRUD
    • MyBatis-Plus 常用注解
    • 条件构造器和常用接口
    • MyBatis-Plus 插件
      • 分页插件
        • 添加配置类
        • 测试
        • 结果
      • xml自定义分页
        • UserMapper
        • UserMapper.xml中编写SQL
        • 测试
        • 结果
      • 乐观锁
        • 场景
        • 乐观锁与悲观锁
        • 模拟修改冲突
        • 数据库中增加商品表
        • 添加数据
        • 添加实体
        • 添加mapper
        • 测试
        • 结果
        • 乐观锁实现流程
        • MyBatis-Plus实现乐观锁
        • 修改实现类
        • 添加乐观锁插件配置
        • 测试结果
        • 优化流程
    • MyBatis-Plus 通用枚举
    • MyBatis-Plus 代码生成器
    • MyBatis-Plus 多数据源
    • MyBatisX插件
  • ShardingSphere

    • ShardingSphere_高性能架构模式
    • ShardingSphere 简介
    • ShardingSphere 主从同步
    • ShardingSphere_JDBC 读写分离
    • ShardingSphere-JDBC垂直分片
    • ShardingSphere-JDBC水平分片
    • 启动ShardingSphere-Proxy
    • ShardingSphere-Proxy读写分离
    • ShardingSphere-Proxy垂直分片
  • studynotes
  • database
  • MyBatis
wufan
2022-04-19
目录

MyBatis-Plus 插件

# MyBatis-Plus 插件🔌

# 分页插件

MyBatis Plus自带分页插件,只要简单的配置即可实现分页功能

# 添加配置类

/**
 * @author frx
 * @version 1.0
 * @date 2022/4/19  11:11
 */
@Configuration
@MapperScan(basePackages = "com.frx01.mybatisplus.mapper")
public class MyBatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //添加分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 测试

/**
 * @author frx
 * @version 1.0
 * @date 2022/4/19  11:21
 */
@SpringBootTest
public class MyBatisPlusPluginsTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testPage(){
        //显示第一页,每页三条数据
        Page<User> page = new Page<User>(1,3);
        userMapper.selectPage(page,null);
        System.out.println(page);
        System.out.println("当前页:"+page.getCurrent());
        System.out.println("获取当前页数据:"+page.getRecords());
        System.out.println("获取总页数:"+page.getPages());
        System.out.println("获取总记录数:"+page.getTotal());
        System.out.println("是否有上一页:"+page.hasPrevious());
        System.out.println("是否有下一页:"+page.hasNext());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# 结果

...
==>  Preparing: SELECT COUNT(*) AS total FROM t_user WHERE is_deleted = 0
==> Parameters: 
<==    Columns: total
<==        Row: 5
<==      Total: 1
==>  Preparing: SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 LIMIT ?
==> Parameters: 3(Long)
<==    Columns: id, name, age, email, is_deleted
<==        Row: 6, 小明, 21, test@atSchool.com, 0
<==        Row: 7, Billie, 24, test5@baomidou.com, 0
<==        Row: 8, 张三, 23, zhangsan@atschool.com, 0
<==      Total: 3
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2ab0702e]
com.baomidou.mybatisplus.extension.plugins.pagination.Page@459f703f
当前页:1
获取当前页数据:[User(id=6, name=小明, age=21, email=test@atSchool.com, isDeleted=0), User(id=7, name=Billie, age=24, email=test5@baomidou.com, isDeleted=0), User(id=8, name=张三, age=23, email=zhangsan@atschool.com, isDeleted=0)]
获取总页数:2
获取总记录数:5
是否有上一页:false
是否有下一页:true
2022-04-19 11:36:03.650  INFO 984 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2022-04-19 11:36:03.674  INFO 984 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Process finished with exit code 0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

01

# xml自定义分页

# UserMapper

#配置mybatis日志
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  #设置mybatis-plus的全局配置
  global-config:
    db-config:
      # 配置MyBatis-Plus操作表的默认前缀
      table-prefix: t_
      # 配置MyBatis-Plus的主键策略
      id-type: auto
  # 配置类型别名所对应的包
  type-aliases-package: com.frx01.mybatisplus.pojo
1
2
3
4
5
6
7
8
9
10
11
12
13

# UserMapper.xml中编写SQL

	<!--Page<User> selectPageVo(@Param("page") Page<User> page,@Param("age") Integer age);-->
    <select id="selectPageVo" resultType="User">
        select uid,user_name,age,email from t_user where age > #{age}
    </select>
1
2
3
4

# 测试

    @Test
    public void testPageVo(){
        Page<User> page = new Page<>(1,3);
        userMapper.selectPageVo(page,20);
        System.out.println("当前页:"+page.getCurrent());
        System.out.println("获取当前页数据:"+page.getRecords());
        System.out.println("获取总页数:"+page.getPages());
        System.out.println("获取总记录数:"+page.getTotal());
        System.out.println("是否有上一页:"+page.hasPrevious());
        System.out.println("是否有下一页:"+page.hasNext());
    }
1
2
3
4
5
6
7
8
9
10
11

# 结果

...
==>  Preparing: SELECT COUNT(*) AS total FROM t_user WHERE age > ?
==> Parameters: 20(Integer)
<==    Columns: total
<==        Row: 6
<==      Total: 1
==>  Preparing: select uid,user_name,age,email from t_user where age > ? LIMIT ?
==> Parameters: 20(Integer), 3(Long)
<==    Columns: uid, user_name, age, email
<==        Row: 3, Tom, 28, test3@baomidou.com
<==        Row: 6, 小明, 21, test@atSchool.com
<==        Row: 7, Billie, 24, test5@baomidou.com
<==      Total: 3
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7158daf2]
当前页:1
获取当前页数据:[User(id=null, name=null, age=28, email=test3@baomidou.com, isDeleted=null), User(id=null, name=null, age=21, email=test@atSchool.com, isDeleted=null), User(id=null, name=null, age=24, email=test5@baomidou.com, isDeleted=null)]
获取总页数:2
获取总记录数:6
是否有上一页:false
是否有下一页:true
2022-04-19 12:16:42.241  INFO 22084 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2022-04-19 12:16:42.295  INFO 22084 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Process finished with exit code 0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 乐观锁

# 场景

一件商品,成本价是80元,售价是100元。老板先是通知小李,说你去把商品价格增加50元。小 李正在玩游戏,耽搁了一个小时。正好一个小时后,老板觉得商品价格增加到150元,价格太 高,可能会影响销量。又通知小王,你把商品价格降低30元。

此时,小李和小王同时操作商品后台系统。小李操作的时候,系统先取出商品价格100元;小王 也在操作,取出的商品价格也是100元。小李将价格加了50元,并将100+50=150元存入了数据 库;小王将商品减了30元,并将100-30=70元存入了数据库。是的,如果没有锁,小李的操作就 完全被小王的覆盖了。

现在商品价格是70元,比成本价低10元。几分钟后,这个商品很快出售了1千多件商品,老板亏1 万多。

# 乐观锁与悲观锁

上面的故事,如果是乐观锁,小王保存价格前,会检查下价格是否被人修改过了。如果被修改过 了,则重新取出的被修改后的价格,150元,这样他会将120元存入数据库。

如果是悲观锁,小李取出数据后,小王只能等小李操作完之后,才能对价格进行操作,也会保证 最终的价格是120元。

# 模拟修改冲突

# 数据库中增加商品表

CREATE TABLE t_product
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
NAME VARCHAR(30) NULL DEFAULT NULL COMMENT '商品名称',
price INT(11) DEFAULT 0 COMMENT '价格',
VERSION INT(11) DEFAULT 0 COMMENT '乐观锁版本号',
PRIMARY KEY (id)
);
1
2
3
4
5
6
7
8

# 添加数据

INSERT INTO t_product (id, NAME, price) VALUES (1, '外星人笔记本', 100);
1

# 添加实体

@Data
public class Product {
    private Integer id;
    private String name;
    private Integer price;
    private Integer version;
}
1
2
3
4
5
6
7

# 添加mapper

public interface ProductMapper extends BaseMapper<Product> {
}
1
2

# 测试

    @Test
    public void testProduct01(){
        //小李查询商品价格
        Product productLi = productMapper.selectById(1);
        System.out.println("小李查询的商品价格:"+productLi.getPrice());
        //小王查询商品价格
        Product productWang = productMapper.selectById(1);
        System.out.println("小王查询的商品价格:"+productWang.getPrice());
        //小李将商品价格加50
        productLi.setPrice(productLi.getPrice()+50);
        productMapper.updateById(productLi);
        //小王将商品价格减去30
        productWang.setPrice(productWang.getPrice()-30);
        productMapper.updateById(productWang);

        //老板查询商品价格
        Product productBoss = productMapper.selectById(1);
        System.out.println("老板查询的商品价格:"+productBoss.getPrice());

    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 结果

==>  Preparing: SELECT id,name,price,version FROM t_product WHERE id=?
小王查询的商品价格:100    
==>  Preparing: SELECT id,name,price,version FROM t_product WHERE id=?
小李查询的商品价格:100
==>  Preparing: SELECT id,name,price,version FROM t_product WHERE id=?
老板查询的商品价格:70  //70替换了150
1
2
3
4
5
6

# 乐观锁实现流程

数据库中添加version字段

取出记录时,获取当前version

SELECT id,`name`,price,`version` FROM product WHERE id=1
1

更新时,version + 1,如果where语句中的version版本不对,则更新失败

UPDATE product SET price=price+50, `version`=`version` + 1 WHERE id=1 AND
`version`=1
1
2

# MyBatis-Plus实现乐观锁

# 修改实现类

@Data
public class Product {
    private Integer id;
    private String name;
    private Integer price;
    @Version //标识乐观锁版本号字段
    private Integer version;
}
1
2
3
4
5
6
7
8

# 添加乐观锁插件配置

@Configuration
@MapperScan(basePackages = "com.frx01.mybatisplus.mapper")
public class MyBatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //添加分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        //添加乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 测试结果

==>  Preparing: SELECT id,name,price,version FROM t_product WHERE id=?
==> Parameters: 1(Integer)
<==    Columns: id, name, price, version
<==        Row: 1, 外星人笔记本, 100, 1
<==      Total: 1
小李查询的商品价格:100
    
==>  Preparing: SELECT id,name,price,version FROM t_product WHERE id=?
==> Parameters: 1(Integer)
<==    Columns: id, name, price, version
<==        Row: 1, 外星人笔记本, 100, 1
<==      Total: 1
小王查询的商品价格:100
    
==>  Preparing: UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?
==> Parameters: 外星人笔记本(String), 150(Integer), 2(Integer), 1(Integer), 1(Integer)
<==    Updates: 1 //小李修改成功,version变为1
    
==>  Preparing: UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?
==> Parameters: 外星人笔记本(String), 70(Integer), 2(Integer), 1(Integer), 1(Integer)
<==    Updates: 0 //小王修改失败了因为小王修改的version为0 找不到了 

==>  Preparing: UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?
==>  Preparing: SELECT id,name,price,version FROM t_product WHERE id=?
==> Parameters: 1(Integer)
<==    Columns: id, name, price, version
<==        Row: 1, 外星人笔记本, 150, 2
<==      Total: 1
老板查询的商品价格:150
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

小李查询商品信息:

SELECT id,name,price,version FROM t_product WHERE id=?

小王查询商品信息:

SELECT id,name,price,version FROM t_product WHERE id=?

小李修改商品价格,自动将version+1

UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?

Parameters: 外星人笔记本(String), 150(Integer), 1(Integer), 1(Long), 0(Integer)

小王修改商品价格,此时version已更新,条件不成立,修改失败

UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?

Parameters: 外星人笔记本(String), 70(Integer), 1(Integer), 1(Long), 0(Integer)

最终,小王修改失败,Boss查询价格:150

SELECT id,name,price,version FROM t_product WHERE id=?

# 优化流程

    @Test
    public void testProduct01(){
        //小李查询商品价格
        Product productLi = productMapper.selectById(1);
        System.out.println("小李查询的商品价格:"+productLi.getPrice());
        //小王查询商品价格
        Product productWang = productMapper.selectById(1);
        System.out.println("小王查询的商品价格:"+productWang.getPrice());
        //小李将商品价格加50
        productLi.setPrice(productLi.getPrice()+50);
        productMapper.updateById(productLi);
        //小王将商品价格减去30
        productWang.setPrice(productWang.getPrice()-30);
        int result = productMapper.updateById(productWang);
        if(result == 0){
            //操作失败,重试,获得版本号
            Product productNew = productMapper.selectById(1);
            productNew.setPrice(productLi.getPrice()-30);
            productMapper.updateById(productNew);
        }
        //老板查询商品价格
        Product productBoss = productMapper.selectById(1);
        System.out.println("老板查询的商品价格:"+productBoss.getPrice());

    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

小李查询商品的价格为100

小王查询商品的价格为100

小李修改商品价格为150,版本号修改为1

小王修改版本0的商品价格失败

小王重新获取版本号

小李修改商品价格为120,版本号修改为2

Boss查询商品价格为150,版本号为2

#MyBatis-Plus
上次更新: 2024/04/21, 09:42:22
条件构造器和常用接口
MyBatis-Plus 通用枚举

← 条件构造器和常用接口 MyBatis-Plus 通用枚举→

最近更新
01
微信支付功能的实现与流程
11-21
02
购物车与结算区域的深入优化与功能完善
11-21
03
购物车与结算区域的功能实现与优化
11-21
更多文章>
Theme by Vdoing | Copyright © 2023-2024 EmmmuaCode | 黔ICP备2022009864号-2
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式