4. MyBatis-Plus核心插件

一、分页插件

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

1、添加配置类

创建config包,创建MybatisPlusConfig.java

package com.indi.mybatisplus.config;

/**
 * 关于持久层的配置
 */
@Configuration
@MapperScan("com.indi.mybatisplus.mapper")  // 扫描 Mapper 文件夹
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

2、添加分页插件

配置类中添加@Bean配置

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

3、测试分页

创建测试类InterceptorTests.java

package com.indi.mybatisplus;

@SpringBootTest
public class InterceptorTests {
    @Resource
    private UserMapper userMapper;

    @Test
    public void testSelectPage() {
        // 参数:当前页 | 每页显示条数
        Page<User> pageParam = new Page<>(2 , 5);

        // 参数:分页对象 | 查询条件
        userMapper.selectPage(pageParam, null);

        List<User> records = pageParam.getRecords();
        records.forEach(System.out::println);

        System.out.println("总记录数:"+ pageParam.getTotal());
        System.out.println("是否存在上一页:"+pageParam.hasPrevious());
        System.out.println("是否存在下一页:"+pageParam.hasNext());
    }
}

4、Tips

  1. MyBatisPlus在分页的时候会执行两条SQL语句,第1条是查询符合条件的总数量count,第2条是进行分页limit,如果第1条SQL查询出来的结果是0,第2条也不会再执行了,算是MyBatisPlus的一个优化。

二、XML自定义分页

1、UserMapper中定义接口方法

UserMapper.java

    /**
     * 查询 : 根据年龄查询用户列表,分页显示
     *
     * @param page 分页对象,xml中可以从里面进行取值,传递参数 Page 即自动分页,必须放在第一位
     * @param age 年龄
     * @return 分页对象
     */
    IPage<User> selectPageByAge(Page<?> page, Integer age);

2、定义XML

之前测试,把里面的变量名改了,所以这个地方需要改成新的值

在这里插入图片描述

UserMapper.xml

	<!--
		查询年龄大于age的用户并分页展示
		这里只需要实现查询逻辑即可,MyBatisPlus会自动实现分页
	-->
	<select id="selectPageByAge" resultType="com.indi.mybatisplus.entity.User">
		select <include refid="Base_Column_List"/>
		from t_user
		where age > #{age}
	</select>

3、测试

InterceptorTests.java

@Test
public void testSelectPageVo(){
    Page<User> pageParam = new Page<>(1,5);
    userMapper.selectPageByPage(pageParam, 10);
    
    List<User> users = pageParam.getRecords();
    users.forEach(System.out::println);
}

在这里插入图片描述

可以看到查询出来的结果,有一部分字段没有成功的映射到实体类的字段当中,比如id、name,那是因为之前在写xml的时候,没有添加映射导致的。有两种解决方案

第一种

  • 添加映射集resultMap,可扩展association、collection

    	<resultMap id="BaseResultMap" type="com.indi.mybatisplus.entity.User">
    		<id property="uid" column="u_id" jdbcType="BIGINT"/>
    		<result property="name" column="username" jdbcType="VARCHAR"/>
    		<!--...-->
    	</resultMap>
    	
    	<select id="selectPageByAge" resultMap="BaseResultMap">
    		select <include refid="Base_Column_List"/>
    		from t_user
    		where age > #{age}
    	</select>	
    

第二种

  • 使用别名,原查询不做任何修改,也可实现效果

    	<sql id="Base_Column_List">
    		uid as id, 
    		`username` as name, 
    		age, 
    		email
    	</sql>
    

结果:成功映射

在这里插入图片描述

三、乐观锁

1、场景

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

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

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

接下来模拟这一过程:

step1:数据库中增加商品表

CREATE TABLE product
(
    id BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    name VARCHAR(30) NULL DEFAULT NULL COMMENT '商品名称',
    price INT(11) DEFAULT 0 COMMENT '价格',
    version INT(11) DEFAULT 0 COMMENT '乐观锁版本号',
    PRIMARY KEY (id)
);
INSERT INTO product (id, NAME, price) VALUES (1, '笔记本', 100);

step2:创建实体类

Product.java

package com.indi.mybatisplus.entity;

@Data
public class Product {
    private Long id;
    private String name;
    private Integer price;
    private Integer version;
}

step3:创建Mapper

ProductMapper.java

package com.indi.mybatisplus.mapper;
public interface ProductMapper extends BaseMapper<Product> {
    
}

step4:测试

InterceptorTests.java

    @Resource
    private ProductMapper productMapper;
    
    @Test
    public void testConcurrentUpdate() {
        // 小李取数据
        Product p1 = productMapper.selectById(1L);

        // 小王取数据
        Product p2 = productMapper.selectById(1L);

        // 小李修改 + 50
        p1.setPrice(p1.getPrice() + 50);
        int result = productMapper.updateById(p1);
        System.out.println("小李修改的结果:" + (result == 1 ? "成功" : "失败"));

        // 小王修改 - 30
        p2.setPrice(p2.getPrice() - 30);
        int result2 = productMapper.updateById(p2);
        System.out.println("小王修改的结果:" + (result2 == 1 ? "成功" : "失败"));

        // 老板看价格
        Product p3 = productMapper.selectById(1L);
        System.out.println("最终价格:"+ p3.getPrice());		// 最终价格被小王修改,直接变成70
    }

2、乐观锁方案

数据库中添加version字段:取出记录时,version字段也要取出来

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

更新时,需要判断当时取出来的version字段与数据库是否一致,一致则更新,不一致则不更新

更新的时候,还需要让version+1

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

具体流程如下:

先把数据库的值还原到100

-- 小李取数据 version = 0
SELECT id,`name`,price,`version` FROM product WHERE id = 1;

-- 小王取数据 version = 0
SELECT id,`name`,price,`version` FROM product WHERE id = 1;

-- 小李改数据 +50 修改成功
UPDATE product SET price=100+50,`version`= 0 + 1 WHERE id = 1 AND `version` = 0;

-- 小王改数据 -30 修改失败
UPDATE product SET price=100-30,`version`= 0 + 1 WHERE id = 1 AND `version` = 0;

-- 小王重新修改
-- 小王取数据 version=1 price = 150
SELECT id,`name`,price,`version` FROM product WHERE id = 1;
-- 小王再修改 修改成功 最终价格120 完成老板要求
UPDATE product SET price=150-30,`version`= 1 + 1 WHERE id = 1 AND `version` = 1;

3、乐观锁实现流程

step1:修改实体类

添加 @Version 注解

Product.java

    @Version
    private Integer version;

step2:添加乐观锁插件

MybatisPlusConfig.java

    interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());//乐观锁

在这里插入图片描述

step3:重新执行测试

先把price还原到100,version改为0,再测试

在这里插入图片描述

虽然没达到老板的最终要求,但是最起码没让老板赔钱。

4、优化流程

失败后重试

InterceptorTests.java

        if (result2 == 0) {
            // 失败重试
            p2 = productMapper.selectById(1L);
            p2.setPrice(p2.getPrice() - 30);
            result2 = productMapper.updateById(p2);
        }

在这里插入图片描述

先把price还原到100,version改为0,再测试:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值