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

功能测试

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

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

相关推荐
相与还31 分钟前
IDEA+SpringBoot实现远程DEBUG到本机
java·spring boot·intellij-idea
Terio_my1 小时前
Spring Boot 缓存技术详解
spring boot·后端·缓存
caibixyy1 小时前
Spring Boot 集成 Kafka 详解
spring boot·kafka
Terio_my3 小时前
Spring Boot 整合 Elasticsearch
spring boot·后端·elasticsearch
majunssz5 小时前
深入剖析Spring Boot依赖注入顺序:从原理到实战
java·数据库·spring boot
Terio_my5 小时前
Spring Boot 缓存与验证码生成
spring boot·spring·缓存
稚辉君.MCA_P8_Java6 小时前
DeepSeek Java 单例模式详解
java·spring boot·微服务·单例模式·kubernetes
疯癫的老码农6 小时前
【小白入门docker】创建Spring Boot Hello World应用制作Docker镜像并运行
java·spring boot·分布式·docker·微服务
PH = 78 小时前
Spring AI整合聊天模型DeepSeek
java·spring boot·后端
计算机毕业设计小帅8 小时前
【2026计算机毕业设计】基于Springboot的医院信息管理系统
spring boot·后端·课程设计