使用
使用步骤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());
}
}