mybatis-plus自动生成器插件,关联分类的删除

使用

使用步骤1.配置数据库

2.选择表 ctrl可以多选,检查字段后确定

 删除分类

1.判断该分类下是否关联相关表,没有直接删除,有抛异常

相关代码

controller的代码
//分类管理删除
    @DeleteMapping
    public R<String> delete(Long ids){

        categoryService.remove(ids);
        return R.success("删除成功");

    }

service接口

自定义接口remove

public interface CategoryService extends IService<Category> {

    public void remove(Long id);
}


service实现类

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;
    /**
     * 根据id删除分类
     * @param id 删除分类的id
     */
    @Override
    public void remove(Long id) {
        //查询分类是否关联菜品,有关联抛出业务异常
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>(); //添加查询条件
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        int count1 = dishService.count(dishLambdaQueryWrapper);

        if (count1>0){
            //存在关联菜品
            throw new CustomException("当前分类关联了菜品,不能删除");
        }

        //查询分类是否关联套餐,有关联抛出业务异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();//添加查询条件
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        int count2 = setmealService.count(setmealLambdaQueryWrapper);

        if (count2>0){
            //存在关联套餐
            throw new CustomException("当前分类关联了套餐,不能删除");
        }

        super.removeById(id);
        //正常删除
    }

2.异常处理,自定义异常,抛出后在自定义全局异常捕获

/**
 * 自定义业务异常类
 */
public class CustomException extends RuntimeException{

    public CustomException(String message){
        super(message);
    }

}



/**
 * 全局异常处理类
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class}) //通知,拦截类上加了@RestController,@Controller注解的异常
@ResponseBody//返回Json格式
@Slf4j
public class GlobalExceptionHandler {

    /**
     * Mysql异常处理方法
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {

        log.error(ex.getMessage());

        if (ex.getMessage().contains("Duplicate entry")) { //sql返回的username重复错误提示
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }

        return R.error("未知错误");
    }

    //分类删除相关异常捕获
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex) {

        log.error(ex.getMessage());
        return R.error(ex.getMessage());

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值