先建一个config包,在建一个类MyBatisPlusConfig
package com.dzqc.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
//添加分页插件
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
//添加乐观锁插件
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return mybatisPlusInterceptor;
}
}
在建一个实体类Product
package com.dzqc.pojo;
import com.baomidou.mybatisplus.annotation.Version;
import lombok.Data;
@Data
public class Product {
private Long id;
private String name;
private Double price;
//标识属性对应的字段作为更新时的版本记录
@Version
private Integer version;
}
在建一个mapper类,ProductMapper接口
package com.dzqc.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.dzqc.pojo.Product;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Repository
@Mapper
public interface ProductMapper extends BaseMapper<Product> {
}
在建一个测试类OpLockTest
package com.dzqc;
import com.dzqc.mapper.ProductMapper;
import com.dzqc.pojo.Product;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class OpLockTest {
@Autowired
private ProductMapper productMapper;
@Test
public void test1(){
//A查询商品
Product productA = productMapper.selectById(1L);
//B查询商品
Product productB = productMapper.selectById(1L);
//A修改价格+50
productA.setPrice(productA.getPrice()+50);
//更新数据
productMapper.updateById(productA);
//B修改价格-30
productB.setPrice(productB.getPrice()-30);
int result = productMapper.updateById(productB);
if (result==0){//更新失败,重试
//更新查询id=1的商品信息
Product product = productMapper.selectById(1L);
//修改价格
product.setPrice(product.getPrice()-30);
//更新数据库
productMapper.updateById(product);
}
//最终价格 预计120
Product productFinal = productMapper.selectById(1L);
System.out.println("商品最终价格:"+productFinal.getPrice());
}
}
测试类结果