乐观锁的具体实现

原理:是通过乐观锁版本号实现的(添加字段version)

//在表中添加字段 version
version  int  11

//在实体类版本号属性添加注解
@Version
@TableField(fill= FieldFill.INSERT)
private Integer version; //版本号
//配置乐观锁插件
@Configuration
@MapperScan("com.leavescai7.demo20201116.mapper")
public class MpConfig {
     //乐观锁插件
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
         return new OptimisticLockerInterceptor();
    }
}

//Handler
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("version",1,metaObject);
}

@Override
public void updateFill(MetaObject metaObject) {
}
}

//测试乐观锁 @Test public void testOptimisticLocker(){ //根据id查询数据 User user = userMapper.selectById(9001); //进行修改 user.setAge(200); userMapper.updateById(user); }

 

 

posted on 2020-11-19 14:01  LeavesCai7  阅读(144)  评论(0)    收藏  举报