feat:库存仓储服务
This commit is contained in:
@@ -54,6 +54,12 @@ public class InventoryDO implements Serializable {
|
||||
*/
|
||||
private Integer remainingStock;
|
||||
|
||||
/**
|
||||
* 乐观锁版本号
|
||||
*/
|
||||
@Version
|
||||
private Integer version;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
|
||||
@@ -1,22 +1,18 @@
|
||||
package pers.amos.mall.route.dal.repository;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import pers.amos.mall.route.dal.dataobject.InventoryDO;
|
||||
|
||||
/**
|
||||
* 库存仓储接口
|
||||
*/
|
||||
public interface InventoryRepository {
|
||||
public interface InventoryRepository extends IService<InventoryDO> {
|
||||
|
||||
/**
|
||||
* 根据库存编码查询
|
||||
*/
|
||||
InventoryDO findByInventoryCode(String inventoryCode);
|
||||
|
||||
/**
|
||||
* 保存库存
|
||||
*/
|
||||
void save(InventoryDO inventoryDO);
|
||||
|
||||
|
||||
/**
|
||||
* 更新库存(乐观锁)
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package pers.amos.mall.route.dal.repository.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import pers.amos.mall.common.log.LogUtil;
|
||||
import pers.amos.mall.route.dal.dataobject.InventoryDO;
|
||||
import pers.amos.mall.route.dal.mapper.InventoryMapper;
|
||||
import pers.amos.mall.route.dal.repository.InventoryRepository;
|
||||
|
||||
/**
|
||||
* 库存Repository实现
|
||||
*/
|
||||
@Repository
|
||||
public class InventoryRepositoryImpl extends ServiceImpl<InventoryMapper, InventoryDO> implements InventoryRepository {
|
||||
|
||||
@Override
|
||||
public InventoryDO findByInventoryCode(String inventoryCode) {
|
||||
LambdaQueryWrapper<InventoryDO> queryWrapper = Wrappers.lambdaQuery(InventoryDO.class)
|
||||
.eq(InventoryDO::getInventoryCode, inventoryCode);
|
||||
|
||||
return this.getOne(queryWrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean updateWithVersion(InventoryDO inventoryDO) {
|
||||
// MyBatis-Plus 的 @Version 注解会自动处理乐观锁
|
||||
// 更新时会自动:
|
||||
// 1. WHERE 条件加上 version = 当前版本
|
||||
// 2. SET version = version + 1
|
||||
// 3. 如果 affected rows = 0,说明版本冲突或库存不足
|
||||
|
||||
// 额外检查:确保剩余库存不为负数
|
||||
if (inventoryDO.getRemainingStock() < 0) {
|
||||
LogUtil.warn("库存更新失败(剩余库存为负), inventoryCode={}, remainingStock={}",
|
||||
inventoryDO.getInventoryCode(), inventoryDO.getRemainingStock());
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean success = this.updateById(inventoryDO);
|
||||
|
||||
if (!success) {
|
||||
LogUtil.warn("库存更新失败(乐观锁冲突), inventoryCode={}, version={}",
|
||||
inventoryDO.getInventoryCode(), inventoryDO.getVersion());
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user