基于 Spring Boot 瑞吉外卖系统开发(五)
基于 Spring Boot 瑞吉外卖系统开发(五)
删除分类
分类列表中每条分类信息右侧提供了一个“删除”按钮,当需要将已经存在的分类信息删除时,可以通过单击“删除”按钮实现。
请求路径为/category
,携带参数id
,请求方法DELETE
每个菜品表(dish)和套餐表(setmeal)都有与之关联分类,所以在删除分类时,需要先检查删除的分类是否关联了菜品或者套餐,如果关联了,此分类不允许删除。实现代码如下。
创建菜品和套餐的Mapper,service,serviceImpl通用接口
@Mapper
public interface DishMapper extends BaseMapper<Dish> {}
@Mapper
public interface SetmealMapper extends BaseMapper<Setmeal> {}
public interface DishService extends IService<Dish> {}
public interface SetmealService extends IService<Setmeal> {}
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>implements DishService {}
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {}
添加分类删除方法
在CategoryService接口中自定义根据分类id删除分类的方法。
public interface CategoryService extends IService<Category> {public void remove(Long id);}
在CategoryServiceImpl类中实现CategoryService接口的remove()方法。
@Service
public class CategoryServiceImplextends ServiceImpl<CategoryMapper, Category> implements CategoryService {@Autowiredprivate DishService dishService;@Autowiredprivate SetmealService setmealService;@Overridepublic void remove(Long id) {QueryWrapper<Dish> query = new QueryWrapper<>();query.eq("category_id", id);int count1 = dishService.count(query);if(count1>0){throw new CustomException("当前分类下关联了菜品,不能删除");}QueryWrapper<Setmeal> query2 = new QueryWrapper<>();query2.eq("category_id", id);int count2 = setmealService.count(query2);if(count2>0){throw new CustomException("当前分类下关联了套餐,不能删除");}super.removeById(id);}}
Controller类中定义删除分类的方法
调用categoryService
中的删除自定义方法remove
。
@DeleteMappingpublic R<String> remove(Long id) {categoryService.remove(id);return R.success("删除成功");}
功能测试
删除“湘菜”,提示当前分类下关联了菜品,不能删除。
删除“商务套餐”,提示删除成功,由于商务套餐分类信息没有被菜品或套餐关联。