mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:59:20 +08:00
feat(ecom-dmb): 商品规格表添加(公司ID,规格编码)复合唯一约束,导入时自动清理重复规格数据
This commit is contained in:
+44
-4
@@ -124,6 +124,44 @@ public class ProductSpecImportHelper {
|
||||
return false;
|
||||
}
|
||||
|
||||
private ProductSpecPO selectSpecByCompanyAndSpecCodeFromDb(Long companyId, String specCode) {
|
||||
if (specCode == null || specCode.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
LambdaQueryWrapper<ProductSpecPO> w = new LambdaQueryWrapper<>();
|
||||
w.eq(ProductSpecPO::getCompanyId, companyId).eq(ProductSpecPO::getSpecCode, specCode);
|
||||
return productSpecService.getOne(w);
|
||||
}
|
||||
|
||||
/**
|
||||
* 插入规格;若触发唯一约束(同公司同 spec_code),则改为从库中加载已存在行。
|
||||
*/
|
||||
private ProductSpecPO insertSpecOrFetchExisting(ProductSpecPO draft, Long companyId,
|
||||
ImportRuntimeContext context) {
|
||||
try {
|
||||
productSpecService.save(draft);
|
||||
return draft;
|
||||
} catch (Exception ex) {
|
||||
if (!isDuplicateKeyException(ex)) {
|
||||
if (ex instanceof RuntimeException re) {
|
||||
throw re;
|
||||
}
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
String code = draft.getSpecCode();
|
||||
if (code == null || code.trim().isEmpty()) {
|
||||
throw new BusinessException(
|
||||
"规格因唯一约束已存在但规格编码为空,无法回查已存在记录");
|
||||
}
|
||||
ProductSpecPO existing = selectSpecByCompanyAndSpecCodeFromDb(companyId, code.trim());
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
throw new BusinessException(
|
||||
"规格因唯一约束已存在但重新查询失败,请稍后重试导入");
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 商品/规格创建 ====================
|
||||
|
||||
/**
|
||||
@@ -139,10 +177,12 @@ public class ProductSpecImportHelper {
|
||||
String trimmedCode = specCode != null ? specCode.trim() : null;
|
||||
String trimmedName = specName != null ? specName.trim() : null;
|
||||
|
||||
// 检查缓存
|
||||
// 检查缓存(插入前再读一次,减少并行线程重复 insert)
|
||||
if (trimmedCode != null) {
|
||||
ProductSpecPO existing = context.specByCodeCache.get(trimmedCode);
|
||||
if (existing != null) return existing;
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
// 创建规格
|
||||
@@ -155,9 +195,9 @@ public class ProductSpecImportHelper {
|
||||
spec.setLinkName(finalSpecName);
|
||||
spec.setProductCost(productCost != null ? productCost : BigDecimal.ZERO);
|
||||
spec.setCreateBy(createBy);
|
||||
productSpecService.save(spec);
|
||||
spec = insertSpecOrFetchExisting(spec, companyId, context);
|
||||
|
||||
// 写入缓存
|
||||
// 写入缓存(有编码时以编码为键;并发冲突回查得到的行也写入)
|
||||
if (trimmedCode != null) {
|
||||
context.specByCodeCache.put(trimmedCode, spec);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user