关于MybatisPlus插件的使用
1 插件
1.1 Mybatis插件机制简介
- (1)插件机制
- Mybatis通过插件(Intercepter)可以做到拦截四大对象(Executor、StatementHandler、ParameterHandler、ResultSetHandler)相关方法的执行,根据需要,完成相关数据的动态改变
- (2)插件原理
- 四大对象的每个对象在创建时,都会执行interceptorChain.pluginAll(),经过每个插件对象的plugin()方法,目的是未当前的四大对象创建代理。代理对象就可以拦截到四大对象相关方法的执行,因为要执行四大对象的方法需要经过代理
1.2 分页插件
- 用于提供数据分页功能
- com.baomidou.mybatisplus.extension.plugins.inner.PaginationInterceptor
- (1)插件注册1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 public class MybatisPlusConfig {
 //插件注册
 
 public MybatisPlusInterceptor mybatisPlusInterceptor() {
 MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
 mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor()); //注册分页插件
 return mpInterceptor;
 }
 }
- (2)分页测试1 
 2
 3
 4
 5
 6
 7
 public void paginationTest() {
 User user = new User();
 Page<User> userPage = user.selectPage(new Page<User>(1, 2), null);
 List<User> records = userPage.getRecords(); //SQL:SELECT id,name,age,email FROM user LIMIT ?
 records.forEach(System.out::println);
 }
1.3 执行分析(阻止攻击)插件
- 分析 delete 和 update语句,防止恶意进行delete update全包操作,建议开发环境中使用
- com.baomidou.mybatisplus.extension.plugins.SqlExplainInterceptor(已过时)
- com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor(新版对应插件)
- (1)插件注册1 
 2
 3
 4
 5
 6
 7
 8//插件注册 
 public MybatisPlusInterceptor mybatisPlusInterceptor() {
 MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
 mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor()); //注册分页插件
 mpInterceptor.addInnerInterceptor(new BlockAttackInnerInterceptor()); //注册阻止恶意攻击插件
 return mpInterceptor;
 }
- (2)插件测试1 
 2
 3
 4
 5
 6
 public void blockAttackTest() {
 User user = new User();
 user.delete(null); //全表删除
 }
 //执行后自动报异常
 
1.4 性能分析插件
- 性能分析拦截器,用于输出每条SQL语句及其执行时间
- com.baomidou.mybatisplus.extension.plugins.PerformanceInterception(新版已删除)
1.5 乐观锁插件
- 当更新一条记录的时候,希望这条记录没有被其他人更新
- 原理是更新数据时,添加一个version进去,执行更新时version + 1,执行后判断版本是否发生改变,改变就更新失败
- com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor
- (1)插件注册1 
 2
 3
 4
 5
 6
 7
 8
 9//插件注册 
 public MybatisPlusInterceptor mybatisPlusInterceptor() {
 MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
 mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor()); //注册分页插件
 mpInterceptor.addInnerInterceptor(new BlockAttackInnerInterceptor()); //注册阻止恶意攻击插件
 mpInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); //注册乐观锁插件
 return mpInterceptor;
 }
- (2)实体类添加version属性1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 public class User extends Model<User> {
 
 private Integer id;
 private String name;
 private Integer age;
 private String email;
 
 private Integer version;
 }
- (3)表结构新增version字段1 
 2alter table user 
 add column version int default 1;
- (4)插件测试1 
 2
 3
 4
 5
 6
 7
 8
 9
 public void optimisticTest() {
 User user = new User();
 user.setId(13);
 user.setName("YJJ");
 user.setVersion(1); //使用乐观锁必须要带version属性
 user.updateById();
 }
