SpringBoot之delete语句的优化

背景

当我们需要进行批量删除的时候,可以通过遍历方式执行多条SQL逐一进行删除也可以选择批量删除只进行一条SQL

实现

  @Transactional
    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> setMealIdsByIds = setMealDishMapper.getSetMealIdsByIds(ids);
        if (setMealIdsByIds != null && setMealIdsByIds.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品表中的菜品数据

        for (Long id : ids) {
            dishMapper.deleteById(id);
            //删除菜品关联的口味数据
            dishFlavorMapper.deleteByDishId(id);
        }
      
    }

SQL

 @Delete("delete from dish where id = #{id}")
    void deleteById(Long id);

优化

@Transactional
    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> setMealIdsByIds = setMealDishMapper.getSetMealIdsByIds(ids);
        if (setMealIdsByIds != null && setMealIdsByIds.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
       
     
        //根据菜品id集合批量删除菜品数据和关联的口味数据
        //sql:delete from dish where id in(?,?,?);
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);
    }

SQL

<delete id="deleteByIds">
        delete from dish where id in
        <foreach collection="ids" open="(" close=")" separator="," item="id">
        #{id}
        </foreach>
    </delete>

你可能感兴趣的:(springboot小知识,spring,boot,后端,java)