| | |
| | | |
| | | @Override |
| | | public int addOrEditProduct(ProductDto productDto) { |
| | | if (ObjectUtils.isEmpty(productDto.getParentId())) { |
| | | throw new IllegalArgumentException("请选择父节点"); |
| | | } |
| | | String productName = StringUtils.trim(productDto.getProductName()); |
| | | if (StringUtils.isEmpty(productName)) { |
| | | throw new IllegalArgumentException("产品名称不能为空"); |
| | |
| | | checkProductNameUnique(productDto.getParentId(), productName, productDto.getId()); |
| | | if (productDto.getId() == null) { |
| | | // 新增产品逻辑 |
| | | // 检查父节点是否存在(可选,根据业务需求) |
| | | // 如果有父节点,检查父节点是否存在 |
| | | if (productDto.getParentId() != null) { |
| | | Product parent = productMapper.selectById(productDto.getParentId()); |
| | | if (parent == null) { |
| | | throw new IllegalArgumentException("父节点不存在,无法添加子产品"); |
| | | } |
| | | } |
| | | return productMapper.insert(productDto); |
| | | } else { |
| | | // 编辑产品逻辑 |
| | | // 检查产品是否存在(可选,根据业务需求) |
| | | // 检查产品是否存在 |
| | | Product existingProduct = productMapper.selectById(productDto.getId()); |
| | | if (existingProduct == null) { |
| | | throw new IllegalArgumentException("要编辑的产品不存在"); |
| | |
| | | |
| | | private void checkProductNameUnique(Long parentId, String productName, Long currentId) { |
| | | LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>(); |
| | | queryWrapper.eq(Product::getParentId, parentId) |
| | | .eq(Product::getProductName, productName) |
| | | .ne(currentId != null, Product::getId, currentId) |
| | | .last("limit 1"); |
| | | queryWrapper.eq(Product::getProductName, productName) |
| | | .ne(currentId != null, Product::getId, currentId); |
| | | // 处理 parentId 为 null 的情况 |
| | | if (parentId == null) { |
| | | queryWrapper.isNull(Product::getParentId); |
| | | } else { |
| | | queryWrapper.eq(Product::getParentId, parentId); |
| | | } |
| | | queryWrapper.last("limit 1"); |
| | | Product duplicateProduct = productMapper.selectOne(queryWrapper); |
| | | if (duplicateProduct != null) { |
| | | throw new IllegalArgumentException("对应的" + productName + "已经存在"); |