基于 Spring Boot 瑞吉外卖系统开发(五)

基于 Spring Boot 瑞吉外卖系统开发(五)

删除分类

分类列表中每条分类信息右侧提供了一个"删除"按钮,当需要将已经存在的分类信息删除时,可以通过单击"删除"按钮实现。

请求路径为/category,携带参数id,请求方法DELETE

每个菜品表(dish)和套餐表(setmeal)都有与之关联分类,所以在删除分类时,需要先检查删除的分类是否关联了菜品或者套餐,如果关联了,此分类不允许删除。实现代码如下。

创建菜品和套餐的Mapper,service,serviceImpl通用接口

java 复制代码
@Mapper
public interface DishMapper extends BaseMapper<Dish> {}
java 复制代码
@Mapper
public interface SetmealMapper extends BaseMapper<Setmeal> {}
java 复制代码
public interface DishService extends IService<Dish> {}
java 复制代码
public interface SetmealService extends IService<Setmeal> {}
java 复制代码
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>
		 implements DishService {}
java 复制代码
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> 
		implements SetmealService {}

添加分类删除方法

在CategoryService接口中自定义根据分类id删除分类的方法。

java 复制代码
public interface CategoryService extends IService<Category> {

    public void remove(Long id);

}

在CategoryServiceImpl类中实现CategoryService接口的remove()方法。

java 复制代码
@Service
public class CategoryServiceImpl
        extends ServiceImpl<CategoryMapper, Category> implements CategoryService 
        {

    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    @Override
    public 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

java 复制代码
    @DeleteMapping
    public R<String> remove(Long id) {
        categoryService.remove(id);
        return R.success("删除成功");
    }

功能测试

删除"湘菜",提示当前分类下关联了菜品,不能删除。

删除"商务套餐",提示删除成功,由于商务套餐分类信息没有被菜品或套餐关联。

相关推荐
自不量力的A同学18 小时前
Spring Boot 4.0.0 正式发布
java·spring boot·后端
q***985220 小时前
什么是Spring Boot 应用开发?
java·spring boot·后端
豆奶特浓621 小时前
Java面试模拟:当搞笑程序员谢飞机遇到电商秒杀与AIGC客服场景
java·spring boot·微服务·面试·aigc·高并发·电商
踏浪无痕1 天前
PageHelper 防坑指南:从兜底方案到根治方案
spring boot·后端
通往曙光的路上1 天前
焚决糟糕篇
java·spring boot·tomcat
6***v4171 天前
spring boot 项目打印sql日志和结果,使用logback或配置文件
spring boot·sql·logback
3***g2051 天前
如何使用Spring Boot框架整合Redis:超详细案例教程
spring boot·redis·后端
s***35301 天前
Spring Boot3.x集成Flowable7.x(一)Spring Boot集成与设计、部署、发起、完成简单流程
java·spring boot·后端
3***16101 天前
【监控】Spring Boot+Prometheus+Grafana实现可视化监控
spring boot·grafana·prometheus
s***4531 天前
SpringBoot返回文件让前端下载的几种方式
前端·spring boot·后端