MyBatis-Plus 对乐观锁提供了原生支持,但对悲观锁没有专门封装,需要借助底层 SQL 或 MyBatis 原生方式实现。

MyBatis-Plus 内置了乐观锁插件,核心思路是:更新时检查版本号,版本号匹配才更新,同时版本号+1。
@Datapublic class Product { private Long id; private String name; private Integer price; @Version // 乐观锁版本号字段 private Integer version;}@Configurationpublic class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // 添加乐观锁拦截器 interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return interceptor; }}// 1. 先查询出实体(version 会被查出来)Product product = productService.getById(1L);// 2. 修改数据product.setPrice(product.getPrice() + 100);// 3. 执行更新(MP 会自动在 WHERE 条件中加上 version = ?)// 生成的 SQL 类似:// UPDATE product SET price=?, version=version+1 WHERE id=? AND version=?boolean success = productService.updateById(product);
| 注意点 | 说明 |
|---|---|
| version 字段类型 | 支持 int、Integer、long、Long、Date、Timestamp |
| 必须查后更新 | updateById(entity) 才会生效,直接 new 一个对象更新不会触发乐观锁 |
| 自增逻辑 | 框架自动 version + 1,无需手动设置 |
| 更新失败 | 如果返回 false,说明数据已被他人修改,需要业务上重试或抛异常 |
// 批量更新时,每个实体的 version 都会参与 WHERE 条件productService.updateBatchById(productList);
MyBatis-Plus 没有提供专门的悲观锁插件,因为悲观锁是数据库层面的机制,需要通过 SQL 的 FOR UPDATE 实现。
在 Mapper 中用 @Select 手写带 FOR UPDATE 的 SQL:
public interface ProductMapper extends BaseMapper<Product> { @Select("SELECT * FROM product WHERE id = #{id} FOR UPDATE") Product selectByIdForUpdate(Long id);}Service 层调用:
@Servicepublic class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService { @Transactional // 必须在事务中,FOR UPDATE 才有效 public void deductStock(Long id) { // 1. 加锁查询 Product product = baseMapper.selectByIdForUpdate(id); // 2. 执行业务逻辑 if (product.getStock() > 0) { product.setStock(product.getStock() - 1); updateById(product); } }}// 不推荐,因为 FOR UPDATE 是写在 SQL 末尾的,QueryWrapper 不好控制位置
// 而且 MP 的 selectOne 等方法不支持直接加 FOR UPDATE
<!-- ProductMapper.xml --><select id="selectByIdForUpdate" resultType="com.example.entity.Product"> SELECT * FROM product WHERE id = #{id} FOR UPDATE</select>| 特性 | 乐观锁 | 悲观锁 |
|---|---|---|
| MP 支持 | ✅ 原生插件支持 | ❌ 需手写 SQL |
| 实现机制 | 版本号控制 | SELECT ... FOR UPDATE |
| 性能 | 高(无锁等待) | 低(有锁竞争、阻塞) |
| 适用场景 | 读多写少、冲突概率低 | 写多读少、冲突概率高、强一致性 |
| 失败处理 | 更新失败需重试 | 排队等待,不会失败 |
| 事务要求 | 非必须 | 必须在事务中 |
优先用乐观锁:绝大多数互联网场景读多写少,乐观锁性能更好,MP 支持也完善。
悲观锁用于强一致性场景:如库存扣减、金融转账等高并发写场景。
乐观锁失败重试:
// 简单的重试机制public boolean updateWithRetry(Product product, int maxRetries) { for (int i = 0; i < maxRetries; i++) { if (productService.updateById(product)) { return true; } // 重新查询最新数据 product = productService.getById(product.getId()); } throw new RuntimeException("更新失败,请重试");}