修改功能
SetmealController
@GetMapping("/{id}")
public R<SetmealDto> get(@PathVariable Long id){
SetmealDto setmealDto = setmealService.getByIdWithDishes(id);
return R.success(setmealDto);
}
@PutMapping
public R<String> update(@RequestBody SetmealDto setmealDto){
log.info(setmealDto.toString());
setmealService.updateWithDishes(setmealDto);
return R.success("修改菜品成功");
}
SetmealService
package com.itheima.reggie.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import java.util.List;
public interface SetmealService extends IService<Setmeal> {
public SetmealDto getByIdWithDishes(Long id);
public void updateWithDishes(SetmealDto setmealDto);
}
SetmealServiceImpl
package com.itheima.reggie.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;
@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
@Autowired
private SetmealDishService setmealDishService;
@Override
public SetmealDto getByIdWithDishes(Long id) {
Setmeal setmeal = super.getById(id);
SetmealDto setmealDto = new SetmealDto();
BeanUtils.copyProperties(setmeal,setmealDto);
LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(SetmealDish::getSetmealId,id);
List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);
setmealDto.setSetmealDishes(setmealDishes);
return setmealDto;
}
@Override
@Transactional
public void updateWithDishes(SetmealDto setmealDto) {
super.updateById(setmealDto);
LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(SetmealDish::getSetmealId,setmealDto.getId());
setmealDishService.remove(queryWrapper);
List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
setmealDishes = setmealDishes.stream().map((item) -> {
item.setSetmealId(setmealDto.getId());
return item;
}).collect(Collectors.toList());
setmealDishService.saveBatch(setmealDishes);
}
}