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

功能测试

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

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

相关推荐
孟婆来包棒棒糖~3 小时前
Maven快速入门
java·spring boot·spring·maven·intellij-idea
杨杨杨大侠6 小时前
附录 1:[特殊字符] Maven Central 发布完整指南:从零到成功部署
java·spring boot·maven
老华带你飞7 小时前
校园交友|基于SprinBoot+vue的校园交友网站(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·校园交友网站
超级小忍11 小时前
使用 GraalVM Native Image 将 Spring Boot 应用编译为跨平台原生镜像:完整指南
java·spring boot·后端
Warren9813 小时前
Spring Boot 整合网易163邮箱发送邮件实现找回密码功能
数据库·vue.js·spring boot·redis·后端·python·spring
Merrick14 小时前
springboot项目service层整理
spring boot
xiaogg367815 小时前
SpringBoot applicationContext.getBeansOfType获取某一接口所有实现类,应用于策略模式
java·spring boot·策略模式
Warren9815 小时前
如何在 Spring Boot 中安全读取账号密码等
java·开发语言·spring boot·后端·安全·面试·测试用例
csdn_aspnet19 小时前
解决 Spring Boot 应用程序中的“无法配置数据源”错误
java·spring boot
至此流年莫相忘21 小时前
TypeReference 泛型的使用场景及具体使用流程
java·开发语言·spring boot