SSM项目之商铺系统-商品与某商品类别关联的实现(十七)

我们完成了商品的product,那么我们之前留了个坑,删除商品类别

我们知道在建表的时候我们将product的product_category_id设置为外键和商品类别表关联

那么要删除商品类别时就需要先将商品下的商品类别id置为空,我们来实现这个功能

实现:

DAO:

通过传入的商品类别id来完成操作

看mapper.xml

    <!--将商品类别下的商品的商品类别字段全部置为空,否则外键约束不能直接删除-->
    <update id="updateProductCategoryToNull">
        UPDATE tb_product
        SET product_category_id=NULL
        WHERE product_category_id = #{productCategoryId}
    </update>

 我们通过商品类别id将商品的商品类别id全置为空

接下来看我们修改后的删除商品类别的方法了:


    //删除商品类别,注意删除商品类别时需要先将该商品类别下的商品id置为空,因为有外键约束,所以直接删除会出错

    @Transactional
    @Override
    public ProductCategoryExecution deleteProductCategory(long productCategoryId, long shopId) {
        try {//删除商品类别下的商品
            int effectNum= productDao.updateProductCategoryToNull(productCategoryId);
            if (effectNum<0)//不能等于0,可能存在商品类别下无商品的情况
            {
                throw  new RuntimeException("商品类别更新失败");
            }
        }catch (ProductOperationException e){
                throw new RuntimeException("deleteProductCategory err"+e.getMessage());
        }

        try {
            int effectNum=productCategoryDao.deleteProductCategory(productCategoryId,shopId);
            if (effectNum<=0){
                throw new ProductCategoryOperationException("商品类别删除失败");
            }else {
                return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS);//成功操作
            }
        }catch (ProductCategoryOperationException e){
            throw new ProductCategoryOperationException("deleteProductCategory error:"+e.getMessage());
        }
    }
}

我们在删除商品类别前,要先将这个商品类别下商品的商品类别id这一字段置为空

猜你喜欢

转载自blog.csdn.net/Sunmeok/article/details/81452460
今日推荐