数据唯一性校验
在业务中,很多场景需要对数据进行唯一性校验,举例说明如下:
- 管理员可以修改商品名称和商品权重(权重高的排在前面),但商品名称和权重不能重复
参数
/*
* 入参,仅列举使用到的参数
*/
public class ProductDTO{
/**
* 商品ID
*/
private String id;
/**
* 商品名称
*/
private String name;
/**
* 商品权重
*/
private Integer weight;
}
/*
* 实体类
*/
public class Product{
/**
* 商品ID
*/
private String id;
/**
* 商品名称
*/
private String name;
/**
* 商品权重
*/
private Integer weight;
/**
* 更新时间
*/
private Integer modified;
}
控制层
/*
* 控制层
*/
private ProductService productService;
/*
* 此处仅做演示,根据实际使用包装返回数据
*/
("test")
public String updateProduct( ProductDTO productDto) {
if(productService.updateProduct(productDto)) {
return "修改成功";
}
return "修改失败";
}
服务层
/*
* 服务层
*/
Boolean updateProduct(ProductDTO productDto);
/*
* 服务层实现类
*/
private ProductMapper productMapper;
public Boolean updateProduct(ProductDTO productDto) {
//查询商品名称是否重合
LambdaQueryWrapper<Product> nameWrapper = Wrappers.lambdaQuery();
nameWrapper.eq(Product::getName, productDto.getName());
nameWrapper.notIn(Product::getId, productDto.getId());
//查询权重是否重合
LambdaQueryWrapper<Product> weightWrapper = Wrappers.lambdaQuery();
weightWrapper.eq(Product::getWeight, productDto.getWeight());
weightWrapper.notIn(Product::getId, productDto.getId());
if (productMapper.selectCount(nameWrapper) > 0) {
throw new ServiceException("该商品已存在");
}
if (productMapper.selectCount(weightWrapper) > 0) {
throw new ServiceException("该权重已存在");
}
Product product = new Product();
BeanUtils.copyProperties(productDto, product);
product.setModified(DateUtils.currTime4Second());
return this.updateById(product);
}