1今天重做reggie准备重做时 发现 菜品删除功能 和 资料上面不一样,我直接 删除
在上面业务逻辑更为清楚 , 删除分类之前 要查看下面是否 有关联相关菜品 和 相关套餐 防止 删除套餐后另外一边查询不到
仔细观察数据库结构
思考业务逻辑 加入我们在 category中删除当前分类 则 我在查询 菜品和套餐时 会发现 category_id 在另外俩个表中存在 则不符合逻辑
所以对当前的代码进行改进
需要引入俩个实体类 以及对应的 Mapper、Service、Controller
然后 在 因为需要很强的业务逻辑处理 所以我们应该在 CategroyService中对其删除方法进行重写
1.在categoryService中进行声明方法
public interface CategoryService extends IService<Category> {
void removeCategory(Long id);
}
2.在实现类categoryServiceImpl对方法进行改写
以下 是我自己写的 业务逻辑代码
/**
* @description 重写 remove 方法 使得 其跟满足逻辑结构
* @param id
* @return void
*/
@Override
public void removeCategory(Long id) {
//1用id对 套餐进行查询 判断其是 菜品分类 还是套餐分类
LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
Category category = this.getById(id);
//查询到是菜品分类的话 应该查询该 分类下有无菜品
if (category.getType().equals(1)){
//用 id 对于 Dish 表中的 Category_id 进行查询
LambdaQueryWrapper<Dish> queryWrapper1 = new LambdaQueryWrapper<>();
queryWrapper1.eq(Dish::getCategoryId, id);
Dish dish = dishService.getOne(queryWrapper1);
if (dish == null){
this.removeById(id);
}
throw new CustomException("当前分类已经关联了菜单 菜品无法删除");
}
//如果当前套餐 应该查看 当前 套餐是否有菜品
if (category.getType().equals(2)){
//用 id 对于 Dish 表中的 Category_id 进行查询
LambdaQueryWrapper<Setmeal> queryWrapper3 = new LambdaQueryWrapper<>();
queryWrapper3.eq(Setmeal::getCategoryId, id);
Setmeal setmeal = setmealService.getOne(queryWrapper3);
if (setmeal == null){
this.removeById(id);
}
throw new CustomException("当前分类 已经关联了套餐 菜品无法删除");
}
}
后面看 黑马外卖给的代码时 发现了
他并没有先查询分类属于什么类型 而是 直接 根据关联的 categoryID 进行查询 俩个表 说实话 我需要先查 分类表 在查询一个表 我举得我的业务逻辑比他好
3.在category中将原来的代码删除
调用我的新方法
4测试
Expected one result (or null) to be returned by selectOne(), but found: 7
发现 自己上面 的categoryServiceImpl方法爆粗 检查后 发现
自己的这句话会查出很多个结果可能 ,,,所以改变策略 还是直接查 比较好 就很傻逼!!!
ok修改代码如下
/**
* @description 重写 remove 方法 使得 其跟满足逻辑结构
* @param id
* @return void
*/
@Override
public void removeCategory(Long id) {
//添加查询条件,根据分类id进行查询菜品数据
LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
int count1 = dishService.count(dishLambdaQueryWrapper);
//如果已经关联,抛出一个业务异常
if(count1 > 0){
throw new CustomException("当前分类下关联了菜品,不能删除");//已经关联菜品,抛出一个业务异常
}
//查询当前分类是否关联了套餐,如果已经关联,抛出一个业务异常
LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
int count2 = setmealService.count(setmealLambdaQueryWrapper);
if(count2 > 0){
throw new CustomException("当前分类下关联了套餐,不能删除");//已经关联套餐,抛出一个业务异常
}
//正常删除分类
super.removeById(id);
}
}
声明 CustomExcption 自定义异常 目的是为了将 义务逻辑错误时 可以报错 弹出提示 ;
然后在 com.hzq,common.GlobalException 定义此类异常如何处理 否则可能会终止程序
@ExceptionHandler(CustomException.class)
public R<String> exceptionHandler(CustomException ex2){
log.info(ex2.toString());
return R.error(ex2.getMessage());
}
然后大功告成测试
IDEA终端输出
完成 删除分类功能
继续开发