实战SSM_O2O商铺_38【商品类别】解除商品与商品类别的关联

概述

实战SSM_O2O商铺_27【商品类别】删除商品类别从Dao到View层的开发 我们留下了一个TODO,在deleteProductCategory方法中,需要先将该商品目录下的商品的类别Id置为空,然后再删除该商品目录。 下面我们在完成了商品的逻辑后,来完善缺失的部分。


Dao层

ProductDao.java

增加updateProductCategory2Null方法

/**
     * 
     * 
     * @Title: updateProductCategory2Null
     * 
     * @Description: 
     *               删除productCategory的时候,需要先将tb_product中的该productCategoryId置为null
     * 
     * @param productCategoryId
     * @param shopId
     * 
     * @return: int
     */
    int updateProductCategory2Null(@Param("productCategoryId") long productCategoryId, @Param("shopId") long shopId);

ProductDao.xml

    <update id="updateProductCategory2Null">
        UPDATE 
            tb_product
        SET 
            product_category_id = null
        WHERE 
            product_category_id = #{productCategoryId}
        AND 
            shop_id = #{shopId}
    </update>   

单元测试

@Test
    public void testUpdateProductCategory2Null() {
        long productCategoryId = 37L;
        long shopId = 5L;
        int effectNum = productDao.updateProductCategory2Null(productCategoryId, shopId);
        Assert.assertEquals(1, effectNum);

        productCategoryId = 36L;
        effectNum = productDao.updateProductCategory2Null(productCategoryId, shopId);
        Assert.assertEquals(6, effectNum);

    }

结合数据库中的数据,设置合理的预期,单元测试通过


Service层完善

ProductCategoryServiceImpl#deleteProductCategory

/**
     * 需要先将该商品目录下的商品的类别Id置为空,然后再删除该商品目录, 因此需要事务控制@Transactional
     */
    @Override
    @Transactional
    public ProductCategoryExecution deleteProductCategory(long productCategoryId, long shopId) throws ProductCategoryOperationException {
        // 第一步 需要先将该商品目录下的商品的类别Id置为空
        try {
            int effectNum = productDao.updateProductCategory2Null(productCategoryId, shopId);
            if (effectNum < 0) {
                throw new ProductCategoryOperationException("商品类别更新失败");
            }
        } catch (Exception e) {
            throw new ProductCategoryOperationException(e.getMessage());
        }
        // 第二步 删除该商品目录
        try {
            int effectNum = productCategoryDao.deleteProductCategory(productCategoryId, shopId);
            if (effectNum > 0) {
                return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS);
            } else {
                return new ProductCategoryExecution(ProductCategoryStateEnum.INNER_ERROR);
            }
        } catch (Exception e) {
            throw new ProductCategoryOperationException(e.getMessage());
        }
    }

单元测试

编写单元测试用例,这里就省略了,因为新增的部分只调用了一个Dao层的方法。


Github地址

代码地址: https://github.com/yangshangwei/o2o

猜你喜欢

转载自blog.csdn.net/yangshangwei/article/details/80968399
今日推荐