@Bean public SqlExplainInterceptor sqlExplainInterceptor(){ SqlExplainInterceptor sqlExplainInterceptor = new SqlExplainInterceptor(); List<ISqlParser> sqlParserList = new ArrayList<>(); sqlParserList.add(new BlockAttackSqlParser()); sqlExplainInterceptor.setSqlParserList(sqlParserList); return sqlExplainInterceptor; }
测试
1 2 3 4 5 6 7 8 9 10
@Autowired private UserMapper userMapper;
@Test publicvoidtestUpdateAll(){ User user = new User(); user.setAge(20); int result = this.userMapper.update(user, null); System.out.println("result = " + result); }
执行更新时, set version = newVersion where version = oldVersion
如果version不对,就更新失败
配置
1 2 3 4
@Bean public OptimisticLockerInterceptor optimisticLockerInterceptor(){ returnnew OptimisticLockerInterceptor(); }
Version字段
为表添加version字段,并且设置初始值为1
1 2 3
ALTERTABLE `tb_user` ADDCOLUMN `version` int(10) NULL AFTER `email`; UPDATE `tb_user` SET `version`='1';
为User实体类添加version字段和注解
1 2
@Version private Integer version;
测试
1 2 3 4 5 6 7 8 9
@Test publicvoidtestUpdateVersion(){ User user = new User(); user.setAge(30); user.setId(2L); user.setVersion(1); // 当前version为1 int result = this.userMapper.updateById(user); System.out.println("result = " + result); }
输出
1 2 3 4 5 6 7 8 9 10 11 12
Time:2 ms - ID:com.coconutnut.demo.mapper.UserMapper.updateById Execute SQL: UPDATE tb_user SET age=30, version=2 WHERE id=2 AND version=1
result = 1
乐观锁插件添加了version条件,并设置新的version为2
如果再执行一次
1 2 3 4 5 6 7 8 9 10 11 12
Time:1 ms - ID:com.coconutnut.demo.mapper.UserMapper.updateById Execute SQL: UPDATE tb_user SET age=30, version=2 WHERE id=2 AND version=1
result = 0
此时version已经是2,不能执行了
正常的使用方式
1 2 3 4 5 6 7 8 9 10 11 12
@Test publicvoidtestUpdateVersion(){ User user = new User(); user.setId(2L); // 查询条件