add(common/common-mybatis): 添加编码唯一性校验工具类,新增 UniqueCodeUtils 工具类,提供通用的编码唯一性校验方法。该方法可用于校验数据库中是否存在重复的编码值,支持新增和更新操作时的编码校验。

- 新增 validateCodeUnique 方法,用于编码唯一性校验
- 方法参数包括:实体对应的 Mapper 实例、需校验的编码值、实体类中编码字段和主键字段的 Lambda 表达式、当前记录的 ID值、重复时的错误提示信息
- 方法内部实现编码校验逻辑,如果编码重复则抛出 ServiceException 异常
- 提供了新增和更新操作时的使用示例
master
zch 2 days ago
parent a675a825d6
commit 4cfff40cb7

@ -0,0 +1,81 @@
package org.dromara.common.mybatis.Utils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.github.yulichang.base.MPJBaseMapper;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.stereotype.Component;
@Component
public class UniqueCodeUtils {
/**
*
*
*
* @param baseMapper MapperbaseMapper
* @param code entity.getDeviceCode()
* @param codeField LambdaDmsBaseDeviceBom::getDeviceCode
* @param idField LambdaDmsBaseDeviceBom::getDeviceBomId
* @param idValue IDnullentity.getDeviceBomId()
* @param errorMessage "设备编码已存在"
* @param <T>
* @param <M> Mapper
* @throws ServiceException errorMessage
*
* 使1 -
* uniqueCodeService.validateCodeUnique(
* baseMapper, // Mapper实例
* entity.getDeviceCode(), // 待校验的编码
* DmsBaseDeviceBom::getDeviceCode, // 编码字段
* DmsBaseDeviceBom::getDeviceBomId,// ID字段
* null, // 新增时ID为null
* "设备编码已存在" // 错误提示
* );
*
* 使2 -
* uniqueCodeService.validateCodeUnique(
* baseMapper, // Mapper实例
* entity.getDeviceCode(), // 待校验的编码
* DmsBaseDeviceBom::getDeviceCode, // 编码字段
* DmsBaseDeviceBom::getDeviceBomId,// ID字段
* entity.getDeviceBomId(), // 更新时传入当前记录ID
* "设备编码已存在" // 错误提示
* );
*/
public static <T, M extends MPJBaseMapper<T>> void validateCodeUnique(
M baseMapper,
String code,
SFunction<T, String> codeField,
SFunction<T, ?> idField,
Object idValue,
String errorMessage
) {
// 1. 首先判断编码是否为空,为空则不需要校验
if (StringUtils.isNotBlank(code)) {
// 2. 构建查询条件包装器
MPJLambdaWrapper<T> wrapper = JoinWrappers.lambda((Class<T>) codeField.getClass())
// 3. 添加编码相等的条件WHERE code = 'xxx'
.eq(codeField, code);
// 4. 如果是更新操作idValue不为空需要排除自身记录
if (idValue != null) {
// 5. 添加ID不等于当前记录ID的条件AND id != xxx
// 这样可以排除当前正在更新的记录,避免误报重复
wrapper.ne(idField, idValue);
}
// 6. 执行查询,获取符合条件的记录数
Long count = baseMapper.selectCount(wrapper);
// 7. 如果存在符合条件的记录count > 0说明编码重复
if (count > 0) {
// 8. 抛出业务异常,中断当前操作
throw new ServiceException(errorMessage);
}
}
}
}
Loading…
Cancel
Save