myBatisPlus 查询 分页 乐观锁以及悲观锁

分页插件
mybp的拦截器 myb的分页插件时,先写了查询功能,对查询功能进行拦截,在实现功能的情况下实现额外的操作

分页参数的三个参数 算法就是( 当前页-1 乘以每页显示的条数) pagesize就是每页显示的条数 index就是当前页的其实索引(跟当前页的页码,和每页显示的条数有关)
当前页的页码,每页显示的条数

配置分页插件 需要spring的配置类的注解,内部插件里面需要指定Mysql的驱动
/** * Date:2022/6/23 * Author:zzy * 配置分页插件 */ @Configuration @MapperScan("com.atguigu.mybatisplus.mapper") public class MyBatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor(){ MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor(); //添加什么插件,要在插件对象红添加内部插件 mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//构造器参数DBType 数据库类型 return mybatisPlusInterceptor; } }
/** * current 当前页的页码 * size 每页显示的条数 */ @Test public void test(){ Page<User> page = new Page<>(2,3); Page<User> page1 = userMapper.selectPage(page, null); System.out.println(page); }
==> Preparing: SELECT COUNT(*) AS total FROM user WHERE is_deleted = 0 ==> Parameters: <== Columns: total <== Row: 6 <== Total: 1 ==> Preparing: SELECT id,name,age,email,is_deleted FROM user WHERE is_deleted=0 LIMIT ?,? ==> Parameters: 3(Long), 3(Long) <== Columns: id, name, age, email, is_deleted <== Row: 8, 小黑, 22, av.com, 0 <== Row: 13, 小明, 27, 小明.com, 0 <== Row: 14, 小明, null, 小明.com, 0 <== Total: 3 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6e91893]
结果limit 2, 3
根据年龄查询用户信息


由于返回的时page类


悲观锁: 小李在操作数据库的时候,小王将一直处于阻塞状态,直到小李更新完毕后小王才能操作数据库
乐观锁:会有一个版本号version 当我们进行更新操作后,数据和版本号都会进行更新,将版本号也作为条件查询

sql实现乐观锁

乐观锁注解

加入乐观锁注解后
==> Preparing: UPDATE product SET name=?, price=?, version=? WHERE id=? AND version=?
==> Parameters: 戴尔(String), 150(Integer), 1(Integer), 1(Integer), 0(Integer)
<== Updates: 1
修改操作第二次版本号不一致,就会导致无法修改成功

@Test public void test03(){ //小李查询商品价格 Product product = productMapper.selectById(1); System.out.println(product.getPrice()+"小李"); Product product1 = productMapper.selectById(1); System.out.println(product1.getPrice()+"小王"); //小李将商品价格+50 product.setPrice(product.getPrice()+50); int i = productMapper.updateById(product); product1.setPrice(product1.getPrice()-30); int result = productMapper.updateById(product1); if(result == 0){ //操作失败,重试 先获取,再更新 Product productNew = productMapper.selectById(1); productNew.setPrice(productNew.getPrice()-30); productMapper.updateById(productNew); } //老板查询 Product productBoss = productMapper.selectById(1); System.out.println(productBoss.getPrice()+"Boss"); }


浙公网安备 33010602011771号