DIshController
/**
* 删除菜品
* 要求:
* 可以批量删除
* 起售中的、关联了套餐的菜品无法删除
* 删除菜品之后,其关联的口味数据也需要删除
* @param ids
* @return
*/
@DeleteMapping
@ApiOperation("删除菜品")
public Result deleteDish(@RequestParam List<Long> ids) {
log.info("菜品正在删除:{}", ids);
dishService.deleteBatch(ids);
return Result.success();
}
DishService
/**
* 删除菜品
* @param ids
*/
void deleteBatch(List<Long> ids);
/**
* 删除菜品
*
* @param ids
*/
// 将这个方法作为一个事务,因为删除菜品涉及三张表,必须三张表都删除成功才提交事务,否则回滚事务
@Transactional
@Override
public void deleteBatch(List<Long> ids) {
// 判断当前菜品是否起售,起售则无法删除
for (Long id : ids) {
Dish dish = dishMapper.getById(id);
if (dish.getStatus().equals(StatusConstant.ENABLE)) {
// 当前菜品已经启用,所以说不能删除,抛出异常
throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
}
}
// 判断当前菜品是否关联了套餐,若关联了套餐那么就无法删除
List<Long> setMealIds = setMealMapper.getSetMealIdByDishId(ids);
if (setMealIds != null && !setMealIds.isEmpty()) {
// 当前菜品关联了套餐,不能删除
throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
}
// 若菜品没有启用并且菜品没有关联套餐,那么可以删除
for (Long id : ids) {
dishMapper.deleteById(id);
// 并且删除菜品相关联的口味数据
dishFlavorMapper.deleteByDishId(id);
}
}
DishMapper
/**
* 根据主键id删除菜品
*
* @param id
*/
@Delete("delete from dish where id = #{id}")
void deleteById(Long id);
/**
* 根据主键id查询菜品
*
* @param id
* @return
*/
@Select("select * from dish where id = #{id}")
Dish getById(Long id);
XML文件
<select id="getSetMealIdByDishId" resultType="java.lang.Long">
select setmeal_id from setmeal_dish where dish_id in
<foreach collection="dishIds" item="dishId" separator="," open="(" close=")">
#{dishId}
</foreach>
</select>

被折叠的 条评论
为什么被折叠?



