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

功能测试

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

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

相关推荐
洋洋技术笔记4 小时前
Spring Boot Web MVC配置详解
spring boot·后端
初次攀爬者1 天前
Kafka 基础介绍
spring boot·kafka·消息队列
用户8307196840821 天前
spring ai alibaba + nacos +mcp 实现mcp服务负载均衡调用实战
spring boot·spring·mcp
Java水解1 天前
SpringBoot3全栈开发实战:从入门到精通的完整指南
spring boot·后端
初次攀爬者2 天前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺2 天前
搞懂@Autowired 与@Resuorce
java·spring boot·后端
Derek_Smart2 天前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot
Nyarlathotep01132 天前
SpringBoot Starter的用法以及原理
java·spring boot
dkbnull3 天前
深入理解Spring两大特性:IoC和AOP
spring boot
洋洋技术笔记3 天前
Spring Boot条件注解详解
java·spring boot