瑞吉外卖-Day4-功能开发(4)

功能开发-菜品管理功能

瑞吉外卖-Day4-功能开发(4)_第1张图片
瑞吉外卖-Day4-功能开发(4)_第2张图片

一、文件上传下载功能

这个系统在多个页面需要上传下载图片,需要一个通用的图片上传下载功能

1.1、文件上传功能介绍

瑞吉外卖-Day4-功能开发(4)_第3张图片
瑞吉外卖-Day4-功能开发(4)_第4张图片
瑞吉外卖-Day4-功能开发(4)_第5张图片

1.2、文件下载功能介绍

瑞吉外卖-Day4-功能开发(4)_第6张图片
瑞吉外卖-Day4-功能开发(4)_第7张图片
瑞吉外卖-Day4-功能开发(4)_第8张图片

1.3、代码实现

瑞吉外卖-Day4-功能开发(4)_第9张图片

1.3.1、导入前端测试页面

瑞吉外卖-Day4-功能开发(4)_第10张图片

1.3.2、方便测试,过滤器放行common

瑞吉外卖-Day4-功能开发(4)_第11张图片

1.3.3、配置文件指定文件上传路径(自定义配置文件变量)

server:
  port: 8080

spring: #spring配置
  application:
    name: reggie_take_out     #项目名称
  datasource:     #数据库连接池
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/reggie?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
      username: root
      password: root

mybatis-plus:
    configuration:
      #在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射
      map-underscore-to-camel-case: true
      log-impl: org.apache.ibatis.logging.stdout.StdOutImpl   #开启日志
    global-config:
      db-config:    #表全局配置
        id-type: ASSIGN_ID    #所有表id使用ASSIGN_ID生成

reggie:
  path: D:\JAVA\SpringBoot\PUL\

1.3.4、commonController

package com.xxxit.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("common")
public class CommonController {

    @Value("${reggie.path}")    // 自己写的类,普通变量用@Value注入
    private String basePath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){    //形参名称必须与前端提交的名称一样
        // file是一个临时文件,需要转存到别的地方不然请求完成后会销毁
        log.info("文件上传:{}",file.toString());

        // 获取图片后缀
        String OriginalFilename = file.getOriginalFilename();
        String suffix = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));

        // 使用雪花生成文件名防止重名 + 后缀
        String fileName = UUID.randomUUID().toString() + suffix;

        // 判断当前路径是否存在,不存在则创建,防止报错
        File dir = new File(basePath);
        if (!dir.exists()){
            dir.mkdirs();
        }

        try{
            file.transferTo(new File(basePath + fileName));
        }catch (Exception ex){
            ex.printStackTrace();
        }

        return R.success(fileName); //返回文件名,好让前端回显请求
    }

    @GetMapping("download")
    public void download(String name, HttpServletResponse response){

        try{
            // 输入流,把文件读进来
            FileInputStream fileInputStream = new FileInputStream(basePath + name);

            // 输出流,通过输出流将文件输出到页面
            ServletOutputStream outputStream = response.getOutputStream();

            // 设置返回类型为图片
            response.setContentType("image/jpeg");

            // 获取字节从0读到最后
            int len = 0;
            byte[] bytes = new byte[1024];

            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            // 关闭资源
            outputStream.close();
            fileInputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

1.3.5、测试

二、新增菜品功能

2.1、需求分析

瑞吉外卖-Day4-功能开发(4)_第12张图片
瑞吉外卖-Day4-功能开发(4)_第13张图片

2.2、数据模型

瑞吉外卖-Day4-功能开发(4)_第14张图片

2.2.1、菜品表

瑞吉外卖-Day4-功能开发(4)_第15张图片
瑞吉外卖-Day4-功能开发(4)_第16张图片

2.2.2、菜品口味表

瑞吉外卖-Day4-功能开发(4)_第17张图片
瑞吉外卖-Day4-功能开发(4)_第18张图片

2.3、代码开发

瑞吉外卖-Day4-功能开发(4)_第19张图片
瑞吉外卖-Day4-功能开发(4)_第20张图片

2.3.1、DishFlavor实体类

package com.xxxit.reggie.entity;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;

/**
菜品口味
 */
@Data
public class DishFlavor implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long id;


    //菜品id
    private Long dishId;


    //口味名称
    private String name;


    //口味数据list
    private String value;


    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;


    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;


    @TableField(fill = FieldFill.INSERT)
    private Long createUser;


    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Long updateUser;


    //是否删除
    private Integer isDeleted;

}

2.3.2、mapper,service,controller构建

mapper

package com.xxxit.reggie.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xxxit.reggie.entity.DishFlavor;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface DishFlavorMapper extends BaseMapper<DishFlavor> {
}

service

package com.xxxit.reggie.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.xxxit.reggie.entity.DishFlavor;

public interface DishFlavorService extends IService<DishFlavor> {
}

serviceImpl

package com.xxxit.reggie.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxit.reggie.entity.DishFlavor;
import com.xxxit.reggie.mapper.DishFlavorMapper;
import com.xxxit.reggie.service.DishFlavorService;
import org.springframework.stereotype.Service;

@Service
public class DishFlavorServiceImpl extends ServiceImpl<DishFlavorMapper, DishFlavor> implements DishFlavorService{
}

controller

package com.xxxit.reggie.controller;

import com.xxxit.reggie.service.DishFlavorService;
import com.xxxit.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 菜品管理
 */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

}

2.3.3、分类管理下拉数组

瑞吉外卖-Day4-功能开发(4)_第21张图片
CategoryController

package com.xxxit.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxxit.reggie.common.R;
import com.xxxit.reggie.entity.Category;
import com.xxxit.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){

        log.info("新增分类:{}",category);

        categoryService.save(category);

        return R.success("新增分类成功");
    }

    /**
     * 分类分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize){

        log.info("分类查询分页功能");

        // 分页构造器
        Page<Category> pageInfo = new Page<>(page,pageSize);

        // 编制查询条件(排序)
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(Category::getSort);

        // 查询
        categoryService.page(pageInfo,lambdaQueryWrapper);

        return R.success(pageInfo);

    }

    /**
     * 删除分类
     * 路径?后参数必须与方法形参同名或者使用注解绑定
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long ids){
        log.info("当前删除的分类id:{}",ids);
        categoryService.remove(ids);
        return R.success("删除成功");
    }

    /**
     * 分类修改
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category){
        log.info("修改分类信息:{}",category.getId());
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 按信息获取对应的分类功能
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        log.info("获取分类管理信息:{}",category.getType());

        // 条件构造器
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        // 添加条件
        lambdaQueryWrapper.eq(category.getType() != null,Category::getType,category.getType());

        // 添加排序
        lambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        // 执行
        List<Category> list = categoryService.list(lambdaQueryWrapper);
        return R.success(list);
    }

}

2.3.4、导入Dto

因为从前端传入的数据,除了dish还有DishFlavor

瑞吉外卖-Day4-功能开发(4)_第22张图片
瑞吉外卖-Day4-功能开发(4)_第23张图片
DishDto

package com.xxxit.reggie.dto;

import com.xxxit.reggie.entity.Dish;
import com.xxxit.reggie.entity.DishFlavor;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;

@Data
public class DishDto extends Dish {

    private List<DishFlavor> flavors = new ArrayList<>();

	// 下面两个属性以后会用到的
	
    private String categoryName;

    private Integer copies;
}

2.3.5、新增菜品功能开发

DishService

package com.xxxit.reggie.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.xxxit.reggie.dto.DishDto;
import com.xxxit.reggie.entity.Dish;

public interface DishService extends IService<Dish> {

    // 新增菜品,同时新增口味,同时操作两张表dish,dish_flavor
    public void saveWithFlavor(DishDto dishDto);

}

DishServiceImpl

package com.xxxit.reggie.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxit.reggie.dto.DishDto;
import com.xxxit.reggie.entity.Dish;
import com.xxxit.reggie.entity.DishFlavor;
import com.xxxit.reggie.mapper.DishMapper;
import com.xxxit.reggie.service.DishFlavorService;
import com.xxxit.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;


    /**
     * 新增菜品,同时保存口味数据
     * @param dishDto
     */
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        // 保存菜品,直接存,向上转型
        dishService.save(dishDto);

        // 因为Dto里面的口味对象,id是空的要所有的加上
        // 1.获取菜品id
        Long DishId = dishDto.getId();

        // 2.获取口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();

        // 3.口味循环加入菜品id
        flavors = flavors.stream().map((item) -> {
            item.setDishId(DishId);
            return item;
        }).collect(Collectors.toList());

        // 保存口味数据到口味表dish_flavor
        dishFlavorService.saveBatch(flavors);
        
    }
}

DishController

package com.xxxit.reggie.controller;

import com.xxxit.reggie.common.R;
import com.xxxit.reggie.dto.DishDto;
import com.xxxit.reggie.service.DishFlavorService;
import com.xxxit.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 菜品管理
 */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        // 保存菜品,直接存,向上转型
        dishService.saveWithFlavor(dishDto);

        return R.success("新增菜品成功");

    }

}

2.3.6、开启事务

瑞吉外卖-Day4-功能开发(4)_第24张图片
瑞吉外卖-Day4-功能开发(4)_第25张图片

2.3.7、测试

三、菜品分页查询

3.1、需求分析

瑞吉外卖-Day4-功能开发(4)_第26张图片
瑞吉外卖-Day4-功能开发(4)_第27张图片

这里需要注意的是,商品分类在页面是显示出来的是名称,而存储在数据库中的
是id,我们自行修改,点击修改后还有很多信息,所以我们可以返回DishDto

3.2、代码开发

package com.xxxit.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxxit.reggie.common.R;
import com.xxxit.reggie.dto.DishDto;
import com.xxxit.reggie.entity.Category;
import com.xxxit.reggie.entity.Dish;
import com.xxxit.reggie.service.CategoryService;
import com.xxxit.reggie.service.DishFlavorService;
import com.xxxit.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;


    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        // 保存菜品,直接存,向上转型
        dishService.saveWithFlavor(dishDto);

        return R.success("新增菜品成功");

    }

    /**
     * 查询菜品分页功能
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("获取菜品分页信息");

        // 构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        // 条件构造器
        LambdaQueryWrapper<Dish> DishQueryWrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        DishQueryWrapper.like(name != null,Dish::getName,name);
        // 添加排序添加
        DishQueryWrapper.orderByDesc(Dish::getUpdateTime);

        // 执行
        dishService.page(pageInfo,DishQueryWrapper);

        // 复制,忽略数据库数据,只拿页码数据条数
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        // 分类id改名字
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> DishDtoRecords = records.stream().map((item) -> {
            // 把Dish的数据复制到dishDto
            DishDto dishDto = new DishDto();

            // 复制
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);

            return dishDto;
        }).collect(Collectors.toList());

        // 把数据放进页面
        dishDtoPage.setRecords(DishDtoRecords);

        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        log.info("查询菜品信息:{}",id);
        DishDto dish = dishService.getByIdWithFlavor(id);
        return R.success(dish);
    }


    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);

        return R.success("新增菜品成功");
    }

}

四、修改菜品功能

4.1、需求分析

瑞吉外卖-Day4-功能开发(4)_第28张图片
瑞吉外卖-Day4-功能开发(4)_第29张图片

4.2、代码开发

4.2.1、根据id获取菜品信息和口味信息

DishService
package com.xxxit.reggie.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.xxxit.reggie.common.R;
import com.xxxit.reggie.dto.DishDto;
import com.xxxit.reggie.entity.Dish;

public interface DishService extends IService<Dish> {

    // 新增菜品,同时新增口味,同时操作两张表dish,dish_flavor
    public void saveWithFlavor(DishDto dishDto);

    // 根据id获取菜品信息和口味数据
    public R<DishDto> getByIdWithFlavor(Long id);

}

DishServiceImpl
package com.xxxit.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxit.reggie.common.R;
import com.xxxit.reggie.dto.DishDto;
import com.xxxit.reggie.entity.Dish;
import com.xxxit.reggie.entity.DishFlavor;
import com.xxxit.reggie.mapper.DishMapper;
import com.xxxit.reggie.service.CategoryService;
import com.xxxit.reggie.service.DishFlavorService;
import com.xxxit.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;


    /**
     * 新增菜品,同时保存口味数据
     * @param dishDto
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        // 保存菜品,直接存,向上转型
        dishService.save(dishDto);

        // 因为Dto里面的口味对象,id是空的要所有的加上
        // 1.获取菜品id
        Long DishId = dishDto.getId();

        // 2.获取口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();

        // 3.口味循环加入菜品id
        flavors = flavors.stream().map((item) -> {
            item.setDishId(DishId);
            return item;
        }).collect(Collectors.toList());

        // 保存口味数据到口味表dish_flavor
        dishFlavorService.saveBatch(flavors);

    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return DishDto
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {

        // 获取菜品信息
        Dish dish = dishService.getById(id);

        // 复制菜品信息到dishDto
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);

        // 获取口味数据
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);


        dishDto.setFlavors(dishFlavorList);

        return dishDto;
    }

}

DishController
package com.xxxit.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxit.reggie.common.R;
import com.xxxit.reggie.dto.DishDto;
import com.xxxit.reggie.entity.Dish;
import com.xxxit.reggie.entity.DishFlavor;
import com.xxxit.reggie.mapper.DishMapper;
import com.xxxit.reggie.service.CategoryService;
import com.xxxit.reggie.service.DishFlavorService;
import com.xxxit.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;


    /**
     * 新增菜品,同时保存口味数据
     * @param dishDto
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        // 保存菜品,直接存,向上转型
        dishService.save(dishDto);

        // 因为Dto里面的口味对象,id是空的要所有的加上
        // 1.获取菜品id
        Long DishId = dishDto.getId();

        // 2.获取口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();

        // 3.口味循环加入菜品id
        flavors = flavors.stream().map((item) -> {
            item.setDishId(DishId);
            return item;
        }).collect(Collectors.toList());

        // 保存口味数据到口味表dish_flavor
        dishFlavorService.saveBatch(flavors);

    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return DishDto
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {

        // 获取菜品信息
        Dish dish = dishService.getById(id);

        // 复制菜品信息到dishDto
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);

        // 获取口味数据
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);


        dishDto.setFlavors(dishFlavorList);

        return dishDto;
    }

}

4.2.2、修改菜品信息

DishService
package com.xxxit.reggie.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.xxxit.reggie.common.R;
import com.xxxit.reggie.dto.DishDto;
import com.xxxit.reggie.entity.Dish;

public interface DishService extends IService<Dish> {

    // 新增菜品,同时新增口味,同时操作两张表dish,dish_flavor
    public void saveWithFlavor(DishDto dishDto);

    // 根据id获取菜品信息和口味数据
    public DishDto getByIdWithFlavor(Long id);

    // 新增菜品,同时新增口味,同时操作两张表dish,dish_flavor
    public void updateWithFlavor(DishDto dishDto);

}

DishServiceImpl
package com.xxxit.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxit.reggie.dto.DishDto;
import com.xxxit.reggie.entity.Dish;
import com.xxxit.reggie.entity.DishFlavor;
import com.xxxit.reggie.mapper.DishMapper;
import com.xxxit.reggie.service.DishFlavorService;
import com.xxxit.reggie.service.DishService;
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
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;


    /**
     * 新增菜品,同时保存口味数据
     * @param dishDto
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        // 保存菜品,直接存,向上转型
        dishService.save(dishDto);

        // 因为Dto里面的口味对象,id是空的要所有的加上
        // 1.获取菜品id
        Long DishId = dishDto.getId();

        // 2.获取口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();

        // 3.口味循环加入菜品id
        flavors = flavors.stream().map((item) -> {
            item.setDishId(DishId);
            return item;
        }).collect(Collectors.toList());

        // 保存口味数据到口味表dish_flavor
        dishFlavorService.saveBatch(flavors);

    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return DishDto
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {

        // 获取菜品信息
        Dish dish = dishService.getById(id);

        // 复制菜品信息到dishDto
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);

        // 获取口味数据
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);


        dishDto.setFlavors(dishFlavorList);

        return dishDto;
    }

    /**
     * 更新菜品信息
     * @param dishDto
     */
    @Override
    public void updateWithFlavor(DishDto dishDto) {

        // 更新菜品,直接存,向上转型
        dishService.updateById(dishDto);

        // 清除以前的所有口味
        // 1.条件构造器
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 2.添加条件
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        // 3.执行
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);

        // 保存口味数据到口味表dish_flavor
        // 因为Dto里面的口味对象,id是空的要所有的加上
        // 1.获取菜品id
        Long DishId = dishDto.getId();

        // 2.获取口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();

        // 3.口味循环加入菜品id
        flavors = flavors.stream().map((item) -> {
            item.setDishId(DishId);
            return item;
        }).collect(Collectors.toList());

        // 保存口味数据到口味表dish_flavor
        dishFlavorService.saveBatch(flavors);

    }
}

DishController
package com.xxxit.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxxit.reggie.common.R;
import com.xxxit.reggie.dto.DishDto;
import com.xxxit.reggie.entity.Category;
import com.xxxit.reggie.entity.Dish;
import com.xxxit.reggie.service.CategoryService;
import com.xxxit.reggie.service.DishFlavorService;
import com.xxxit.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;


    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        // 保存菜品,直接存,向上转型
        dishService.saveWithFlavor(dishDto);

        return R.success("新增菜品成功");

    }

    /**
     * 查询菜品分页功能
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("获取菜品分页信息");

        // 构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        // 条件构造器
        LambdaQueryWrapper<Dish> DishQueryWrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        DishQueryWrapper.eq(name != null,Dish::getName,name);
        // 添加排序添加
        DishQueryWrapper.orderByDesc(Dish::getUpdateTime);

        // 执行
        dishService.page(pageInfo,DishQueryWrapper);

        // 复制,忽略数据库数据,只拿页码数据条数
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        // 分类id改名字
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> DishDtoRecords = records.stream().map((item) -> {
            // 把Dish的数据复制到dishDto
            DishDto dishDto = new DishDto();

            // 复制
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);

            return dishDto;
        }).collect(Collectors.toList());

        // 把数据放进页面
        dishDtoPage.setRecords(DishDtoRecords);

        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        log.info("查询菜品信息:{}",id);
        DishDto dish = dishService.getByIdWithFlavor(id);
        return R.success(dish);
    }


    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);

        return R.success("新增菜品成功");
    }

}

4.3测试

你可能感兴趣的:(SpringBoot项目,spring,spring,boot,mvc,mybatis,java)