• MybatisPlus常用插件


    分页插件

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

    添加配置类 MyBatisPlusConfig

    package com.dawn.mybatisplus.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.dawn.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
    • 18
    • 19
    • 20
    • 21
    • 22

    编写测试方法

    @Test
    public void testPage(){
        //设置分页参数
        //new Page()中的两个参数分别是当前页码,每页显示数量
        Page page = new Page<>(1, 2);
        userMapper.selectPage(page, null);
        //获取分页数据
        List users = page.getRecords();
        users.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());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    控制台打印查询结果

    image-20220730005512991

    XML自定义分页

    上面调用的是 MyBatis-Plus 提供的带有分页的方法,那么我们自己定义的方法如何实现分页呢?

    UserMapper 接口中定义一个方法

    /**
     * 根据年龄查询用户列表,分页显示
     * @param page 分页对象,xml中可以从里面进行取值,传递参数 Page 即自动分页,必须放在第一位
     * @param age 年龄
     * @return
     */
    Page selectPageVO(@Param("page") Page page, @Param("age") Integer age);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    UserMapper.xml 中编写 SQL 实现该方法。

    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.dawn.mybatisplus.mapper.UserMapper">
    
        <select id="selectPageVO" resultType="com.dawn.mybatisplus.pojo.User">
            select uid ,username as name,age,email from t_user where age > #{age}
        select>
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    编写测试方法

    @Test
    public void testPageVo(){
        //设置分页参数
        Page page = new Page<>(1, 2);
        userMapper.selectPageVO(page, 17);
        //获取分页数据
        List users = page.getRecords();
        users.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());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    控制台打印查询结果

    image-20220730010633667

    乐观锁

    作用:当要更新一条记录的时候,希望这条记录没有被别人更新

    乐观锁的实现方式:

    • 取出记录时,获取当前 version
    • 更新时,带上这个 version
    • 执行更新时, set version = newVersion where version = oldVersion
    • 如果 version 不对,就更新失败

    场景

    • 一件商品,成本价是 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 '价格', 
        PRIMARY KEY (id) 
    );
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    添加一条数据

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

    添加一个实体类 Product

    package com.dawn.mybatisplus.pojo;
    
    import com.baomidou.mybatisplus.annotation.TableName;
    import lombok.Data;
    
    @Data
    @TableName("t_product")
    public class Product {
        private Long id;
        private String name;
        private Integer price;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    添加一个 Mapper 接口 ProductMapper

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

    测试方法

    @Test
    public void testProduct01(){
        //1.小李获取商品价格
        Product productLi = productMapper.selectById(1L);
        System.out.println("小李获取的商品价格为:" + productLi.getPrice());
    
        //2.小王获取商品价格
        Product productWang = productMapper.selectById(1L);
        System.out.println("小王获取的商品价格为:" + productWang.getPrice());
    
        //3.小李修改商品价格+50
        productLi.setPrice(productLi.getPrice() + 50);
        productMapper.updateById(productLi);
    
        //4.小王修改商品价格-30
        productWang.setPrice(productWang.getPrice() - 30);
        productMapper.updateById(productWang);
    
        //5.老板查询商品价格
        Product productBoss = productMapper.selectById(1L);
        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

    控制台打印查询结果

    image-20220730011854108

    乐观锁解决问题

    数据库中添加 version 字段。

    • 取出记录时,获取当前 version

      SELECT id,`name`,price,`version` FROM product WHERE id=sql1
      
      • 1
    • 更新时,version + 1,如果 where 语句中的 version 版本不对,则更新失败

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

    修改实体类,添加 version 字段,并添加 @version 注解

    package com.dawn.mybatisplus.pojo;
    
    import com.baomidou.mybatisplus.annotation.TableName;
    import com.baomidou.mybatisplus.annotation.Version;
    import lombok.Data;
    
    @Data
    @TableName("t_product")
    public class Product {
        private Long id;
        private String name;
        private Integer price;
        @Version
        private Integer version;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    添加乐观锁插件配置

    @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

    再次执行测试方法

    小李查询商品信息:
    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)
    
    最终,小王修改失败,老板查询价格:150
    SELECT id,name,price,version FROM t_product WHERE id=?
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    优化执行流程

    @Test
    public void testProduct01(){
        //1.小李获取商品价格
        Product productLi = productMapper.selectById(1L);
        System.out.println("小李获取的商品价格为:" + productLi.getPrice());
    
        //2.小王获取商品价格
        Product productWang = productMapper.selectById(1L);
        System.out.println("小王获取的商品价格为:" + productWang.getPrice());
    
        //3.小李修改商品价格+50
        productLi.setPrice(productLi.getPrice() + 50);
        int result1 = productMapper.updateById(productLi);
        System.out.println("小李修改的结果:" + result1);
        
        //4.小王修改商品价格-30
        productWang.setPrice(productWang.getPrice() - 30);
        int result2 = productMapper.updateById(productWang);
        System.out.println("小王修改的结果:" + result2);
        if (result2 == 0){
            //失败重试,重新获取version并更新
            productWang = productMapper.selectById(1L);
            productWang.setPrice(productWang.getPrice() - 30);
            result2 = productMapper.updateById(productWang);
        }
        System.out.println("小王修改重试的结果:" + result2);
        
        //5.老板查询商品价格
        Product productBoss = productMapper.selectById(1L);
        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
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    image-20220730013409225

    Mybatis X插件

    MyBatis-Plus 为我们提供了强大的 mapper 和 service 模板,能够大大的提高开发效率。

    但是在真正开发过程中,MyBatis-Plus 并不能为我们解决所有问题,我们还是需要自己去编写代码和 SQL 语句,我们该如何快速的解决这个问题呢,这个时候可以使用 MyBatisX 插件。

    MyBatisX 一款基于 IDEA 的快速开发插件,为效率而生。

    MyBatisX 插件用法:https://baomidou.com/pages/ba5b24/

    安装MyBatisX插件

    打开 IDEA,File-> Setteings->Plugins->MyBatisX,搜索栏搜索 MyBatisX 然后安装。

    image-20220730015520448

    快速生成代码

    新建一个 SpringBoot 项目引入依赖(创建工程时记得勾选 lombok 及 mysql 驱动)

    <dependency>
        <groupId>com.baomidougroupId>
        <artifactId>mybatis-plus-boot-starterartifactId>
        <version>3.5.1version>
    dependency>
    
    <dependency>
        <groupId>com.baomidougroupId>
        <artifactId>dynamic-datasource-spring-boot-starterartifactId>
        <version>3.5.0version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    配置数据源信息

    spring:
      datasource:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false
        username: root
        password: 123456
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在 IDEA 中与数据库建立链接

    image-20220730135256086

    填写数据库信息并保存

    image-20220730135556530

    找到我们需要生成的表点击右键

    image-20220730135731073

    填写完信息以后下一步

    image-20220730135957848

    继续填写信息

    image-20220730140317515

    大功告成

    image-20220730140402233

    快速生成CRUD

    MyBaitsX 可以根据我们在 Mapper 接口中输入的方法名快速帮我们生成对应的 sql 语句

    image-20220730140504603

    生成的 SQL 语句

    image-20220730140550855

  • 相关阅读:
    js中使用getElementsByClassName获取class对象
    mybatis入门
    Appium —— 初识移动APP自动化测试框架Appium
    Mysql中常用的sql语句(适合萌新学习)
    牛客网刷题笔记三 寻找第K大+两数之和+合并两个排序的链表+用两个栈实现队列
    Junit单元测试框架
    跨模态检索2023年最新顶会论文汇总
    苹果悄悄推出了一个改变一切的新银行杀手储蓄账户
    Scala 基础 (四):函数式编程【从基础到高阶应用】
    Nginx Proxy代理
  • 原文地址:https://blog.csdn.net/qq_42057154/article/details/126992388