基于 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("删除成功");
    }

功能测试

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

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

相关推荐
星落zx1 小时前
Spring Boot 多模型集成:优雅调用全球主流大模型
人工智能·spring boot·chatgpt
一杯奶茶¥1 小时前
水果销售网站 CRM客户信息管理系统 超市管理系 酒店管理系统 健身房管理系统 在线音乐网站 校园招聘系统
java·vue.js·spring boot·mysql·spring·java项目
进阶的小名2 小时前
Spring Boot SSE + Nginx 配置:解决 EventSource 不实时返回、连接超时、流式响应被缓冲问题
spring boot·后端·nginx
我登哥MVP3 小时前
SpringCloud Alibaba 核心组件解析:服务链路追踪
java·spring boot·后端·spring·spring cloud·java-ee·maven
范什么特西3 小时前
Spring boot细节
java·spring boot·后端
java1234_小锋4 小时前
请描述 Spring Boot 的启动流程,包括 SpringApplication 的初始化和 run 方法的核心步骤。
java·数据库·spring boot
霸道流氓气质5 小时前
Spring Boot 国际化(i18n)完全指南
java·spring boot·后端
Flittly5 小时前
【AgentScope Java新手村系列】(9)SpringBoot集成
java·spring boot·spring
杨运交6 小时前
[033][缓存模块]基于 Redisson 的租户隔离 Redis Key 前缀设计
spring boot