【苍穹外卖】项目实战Day03

向右看齐 2024-05-06 09:57 131阅读 0赞

? 本文由 程序喵正在路上 原创,CSDN首发!
? 系列专栏:苍穹外卖项目实战
? 首发时间:2024年5月4日
? 欢迎关注?点赞?收藏?留言?

目录

  • 公共字段自动填充
    • 问题分析
    • 解决思路
    • 代码开发
    • 功能测试
  • 新增菜品
    • 需求分析和设计
    • 代码开发
    • 功能测试
  • 菜品分页查询
    • 需求分析和设计
    • 代码开发
    • 功能测试
  • 删除菜品
    • 需求分析和设计
    • 代码开发
    • 代码优化
    • 功能测试
  • 修改菜品
    • 需求分析和设计
    • 代码开发
    • 功能测试
  • 菜品启售停售
    • 需求分析和设计
    • 代码开发
    • 功能测试

公共字段自动填充

问题分析

在前面的业务表中,比如表 employeecategory 中,我们可以发现一些公共字段,这些字段在后面的业务表中也同样存在:

在这里插入图片描述

这些公共字段在某些操作中都需要设置,而且设置的代码都是一样的

在这里插入图片描述

那么就出现了问题:代码冗余、不便于后期维护

  • 工程中存在多段相同的代码
  • 如果后期我们需要对业务表进行修改,涉及到这些公共字段,进行修改也是非常麻烦的

解决思路

我们发现,这些公共字段的设置只会出现在特定的操作中,比如 create_timecreate_user 只会出现在 insert 操作中。

在这里插入图片描述

所以,我们的想法是将其统一处理。

具体思路:

  • 自定义注解 AutoFill,用于标识需要进行公共字段自动填充的方法
  • 自定义切面类 AutoFillAspect,统一拦截加入了 AutoFill 注解的方法,通过反射为公共字段赋值
  • Mapper 中需要处理公共字段的方法上加入 AutoFill 注解
  • 涉及技术点:枚举、注解、AOP、反射

代码开发

  1. 创建一个专门用来存放自定义注解的包 annotation,在包下创建自定义注解 AutoFill

    在这里插入图片描述

    1. import com.sky.enumeration.OperationType;
    2. import java.lang.annotation.ElementType;
    3. import java.lang.annotation.Retention;
    4. import java.lang.annotation.RetentionPolicy;
    5. import java.lang.annotation.Target;
    6. @Target(ElementType.METHOD) //只作用于方法上
    7. @Retention(RetentionPolicy.RUNTIME) //表示被该注解修饰的注解在运行时保留,即可以通过反射机制在运行时获取这些注解的信息
    8. public @interface AutoFill {
    9. //定义注解的属性为数据库操作类型: UPDATE INSERT
    10. //OperationType在包com.sky.enumeration中
    11. OperationType value();
    12. }
  2. 创建一个专门用来存放切面类的包 aspect,在包下创建切面类 AutoFillAspect

    1. import com.sky.annotation.AutoFill;
    2. import com.sky.constant.AutoFillConstant;
    3. import com.sky.context.BaseContext;
    4. import com.sky.enumeration.OperationType;
    5. import lombok.extern.slf4j.Slf4j;
    6. import org.aspectj.lang.JoinPoint;
    7. import org.aspectj.lang.annotation.Aspect;
    8. import org.aspectj.lang.annotation.Before;
    9. import org.aspectj.lang.annotation.Pointcut;
    10. import org.aspectj.lang.reflect.MethodSignature;
    11. import org.springframework.stereotype.Component;
    12. import java.lang.reflect.Method;
    13. import java.time.LocalDateTime;
    14. /**
    15. * 自定义切面,实现公共字段自动填充处理逻辑
    16. */
    17. @Aspect //切面类
    18. @Component //标记为Spring管理的Bean
    19. @Slf4j //日志
    20. public class AutoFillAspect {
    21. //切入点
    22. /**
    23. * execution(* com.sky.mapper.*.*(..)): 切点表达式, 方法返回值为任意, 匹配com.sky.mapper包下所有类和接口,
    24. * 参数为任意
    25. *
    26. * @annotation(com.sky.annotation.AutoFill): 注解匹配表达式, 拦截带有AutoFill注解的方法
    27. */
    28. @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    29. public void autoFillPointCut() {
    30. }
    31. /**
    32. * 前置通知:在通知中进行公共字段的赋值
    33. *
    34. * @param joinPoint
    35. */
    36. @Before("autoFillPointCut()")
    37. public void autoFill(JoinPoint joinPoint) {
    38. log.info("公共字段自动填充...");
    39. //获取到当前被拦截的方法上的数据库操作类型
    40. MethodSignature signature = (MethodSignature) joinPoint.getSignature(); //方法的签名对象
    41. AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class); //获取方法上的注解对象
    42. OperationType operationType = autoFill.value(); //获取数据库操作类型
    43. //获取到当前被拦截的方法的参数——实体对象, 我们约定在定义方法时, 实体对象放在第一位
    44. Object[] args = joinPoint.getArgs();
    45. if (args == null || args.length == 0) return;
    46. Object entity = args[0]; //获取实体对象
    47. //准备赋值的数据
    48. LocalDateTime now = LocalDateTime.now();
    49. Long currentId = BaseContext.getCurrentId();
    50. //根据当前不同的操作类型, 为对应的属性通过反射来赋值
    51. if (operationType == OperationType.INSERT) {
    52. //当前执行的是insert操作, 为4个字段赋值
    53. try {
    54. //获取set方法对象——Method
    55. Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
    56. Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
    57. Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
    58. Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
    59. //通过反射调用目标对象的方法
    60. setCreateTime.invoke(entity, now);
    61. setUpdateTime.invoke(entity, now);
    62. setCreateUser.invoke(entity, currentId);
    63. setUpdateUser.invoke(entity, currentId);
    64. } catch (Exception e) {
    65. log.info("公共字段自动填充失败:{}", e.getMessage());
    66. }
    67. } else if (operationType == OperationType.UPDATE) {
    68. //当前执行的是update操作, 为2个字段赋值
    69. try {
    70. //获取set方法对象——Method
    71. Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
    72. Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
    73. //通过反射调用目标对象的方法
    74. setUpdateTime.invoke(entity, now);
    75. setUpdateUser.invoke(entity, currentId);
    76. } catch (Exception e) {
    77. log.info("公共字段自动填充失败:{}", e.getMessage());
    78. }
    79. }
    80. }
    81. }
  3. EmployeeMapperCategoryMapper 中数据库操作类型为 insertupdate 的方法加上自定义的注解 @AutoFill(value = OperationType.INSERT),类型记得别写错;然后,原先代码 Service 层中给这些公共字段赋值的代码就可以删掉了。

功能测试

直接通过前后端联调测试,通过观察控制台输出的SQL来确定公共字段填充是否完成;也可以直接在前端页面观察插入和修改操作后时间是否改变来确认。

新增菜品

需求分析和设计

产品原型:

在这里插入图片描述

业务规则:

  • 菜品名称必须是唯一的
  • 菜品必须属于某个分类下,不能单独存在
  • 新增菜品时可以根据情况选择菜品的口味
  • 每个菜品必须对应一张图片

接口设计:

  • 根据类型查询分类(已开发)

    在这里插入图片描述

  • 文件上传

    在这里插入图片描述

  • 新增菜品

在这里插入图片描述

数据库设计(dish菜品表和dish_flavor口味表):

在这里插入图片描述

代码开发

开发文件上传接口

在这里插入图片描述

首先,我们需要配置阿里云OSS的相关信息,如果你忘了阿里云OSS的相关内容,可以查看这篇文章 ,请配置自己的OSS信息,图中配置信息无效:

在这里插入图片描述

在我们写这些配置的时候,会发现有提示信息,但是这些属性并不是框架自带,为什么会有提示信息呢?

其实这是因为项目的 com.sky.properties 包下有一个配置属性类 AliOssProperties

在这里插入图片描述

通过使用 @ConfigurationProperties 注解,可以将配置文件中以 sky.alioss 前缀开头的属性映射到该类的实例中。然后,可以在 Spring Boot 应用程序中注入 AliOssProperties 类的实例,以便在应用程序中使用阿里云 OSS 的相关配置信息,比如访问端点 (endpoint)、访问密钥 (accessKeyIdaccessKeySecret) 以及存储桶名称 (bucketName) 等。

同时,项目中还有一个使用阿里云 OSS 必须有的工具类,它是由官方代码改造而来,实现的功能为上传文件到阿里云 OSS 并返回该文件的外部访问路径:

在这里插入图片描述
接下来,我们来开发文件上传接口,首先,我们要写一个配置类,用于配置阿里云对象存储服务(OSS)相关的 Bean,后面我们需要用到这个 Bean

你可能会好奇为什么要写成一个配置类,好像普通的类就能实现相同的功能? 如果你不好奇,可以直接去看配置类的代码。

将类声明为配置类的一个主要目的是使其成为 Spring 容器的一部分,从而可以利用 Spring 的依赖注入和管理功能。这样做有几个好处:

  1. 依赖注入管理: 声明为配置类的 Bean 可以在应用程序的整个生命周期内由 Spring 容器进行管理。这意味着可以在应用程序的其他组件中轻松地注入和使用这些 Bean,而不需要手动创建对象。
  2. 组件化: 将相关的配置信息和对象创建逻辑放在一个配置类中有助于更好地组织代码结构,并将关注点分离。这样做可以使代码更易于维护和理解。
  3. 条件化装配: 使用 Spring 的条件化装配功能(如@ConditionalOnMissingBean)可以根据特定条件决定是否创建 Bean,从而实现更灵活的 Bean 创建和管理。
  4. 集成测试: 在单元测试和集成测试中,可以通过模拟和替换 Bean 来轻松测试应用程序的不同部分,而无需更改源代码。

虽然可以手动创建对象来使用,但使用 Spring 的依赖注入机制能够提供更好的可维护性、灵活性和测试性,因此在大多数情况下,将类声明为 Spring 的配置类是更好的选择。

在这里插入图片描述

  1. import com.sky.properties.AliOssProperties;
  2. import com.sky.utils.AliOssUtil;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. @Configuration //配置类
  8. @Slf4j
  9. public class OssConfiguration {
  10. /**
  11. * 通过spring管理对象
  12. *
  13. * @param aliOssProperties
  14. * @return
  15. */
  16. @Bean
  17. @ConditionalOnMissingBean //只有当容器中不存在名为aliOssUtil的Bean时才创建该Bean, 防止重复创建
  18. public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties) {
  19. log.info("开始创建阿里云OSS工具类对象...");
  20. return new AliOssUtil(aliOssProperties.getEndpoint(),
  21. aliOssProperties.getAccessKeyId(),
  22. aliOssProperties.getAccessKeySecret(),
  23. aliOssProperties.getBucketName());
  24. }
  25. }

文件上传这个接口在其他模块中也有可能会使用到,所以我们将其写在一个通用的控制类 CommonController 中。

  1. import com.sky.constant.MessageConstant;
  2. import com.sky.result.Result;
  3. import com.sky.utils.AliOssUtil;
  4. import io.swagger.annotations.Api;
  5. import io.swagger.annotations.ApiOperation;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.web.bind.annotation.PostMapping;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RestController;
  11. import org.springframework.web.multipart.MultipartFile;
  12. import java.util.UUID;
  13. /**
  14. * 通用接口
  15. */
  16. @RestController
  17. @RequestMapping("/admin/common")
  18. @Slf4j
  19. @Api(tags = "通用接口")
  20. public class CommonController {
  21. @Autowired
  22. private AliOssUtil aliOssUtil;
  23. /**
  24. * 文件上传
  25. *
  26. * @param file
  27. * @return
  28. */
  29. @PostMapping("/upload")
  30. @ApiOperation("文件上传")
  31. public Result<String> upload(MultipartFile file) {
  32. log.info("文件上传:{}", file.getName());
  33. String originalFilename = file.getOriginalFilename(); //原始文件名
  34. String extension = originalFilename.substring(originalFilename.lastIndexOf(".")); //获取文件后缀
  35. //生成一个独一无二的文件名
  36. String newFileName = UUID.randomUUID().toString() + extension;
  37. //将文件上传到阿里云
  38. try {
  39. String filePath = aliOssUtil.upload(file.getBytes(), newFileName);
  40. return Result.success(filePath);
  41. } catch (Exception e) {
  42. log.error("文件上传失败:{}", e.getMessage());
  43. }
  44. return Result.error(MessageConstant.UPLOAD_FAILED);
  45. }
  46. }

ps:建议配置单个文件最大上传大小和单个请求最大上传大小:

  1. spring:
  2. servlet:
  3. multipart:
  4. max-file-size: 10MB #单个文件最大上传大小
  5. max-request-size: 100MB #单个请求最大上传大小

开发新增菜品接口

根据新增菜品接口设计对应的DTO(项目中已开发):

在这里插入图片描述

新建 DishController,在其中创建新增菜品方法:

  1. import com.sky.dto.DishDTO;
  2. import com.sky.result.Result;
  3. import com.sky.service.DishService;
  4. import io.swagger.annotations.Api;
  5. import io.swagger.annotations.ApiOperation;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.web.bind.annotation.PostMapping;
  9. import org.springframework.web.bind.annotation.RequestBody;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RestController;
  12. @RestController
  13. @RequestMapping("/admin/dish")
  14. @Api(tags = "菜品相关接口")
  15. @Slf4j
  16. public class DishController {
  17. @Autowired
  18. private DishService dishService;
  19. /**
  20. * 新增菜品
  21. *
  22. * @param dishDTO
  23. * @return
  24. */
  25. @PostMapping
  26. @ApiOperation("新增菜品")
  27. public Result<String> save(@RequestBody DishDTO dishDTO) {
  28. log.info("新增菜品:{}", dishDTO);
  29. dishService.saveWithFlavor(dishDTO);
  30. return Result.success();
  31. }
  32. }

DishService 接口中声明新增菜品方法:

  1. import com.sky.dto.DishDTO;
  2. public interface DishService {
  3. /**
  4. * 新增菜品和对应的口味
  5. * @param dishDTO
  6. */
  7. void saveWithFlavor(DishDTO dishDTO);
  8. }

DishServiceImpl 中实现新增菜品方法:

  1. import com.sky.dto.DishDTO;
  2. import com.sky.entity.Dish;
  3. import com.sky.entity.DishFlavor;
  4. import com.sky.mapper.DishFlavorMapper;
  5. import com.sky.mapper.DishMapper;
  6. import com.sky.service.DishService;
  7. import org.springframework.beans.BeanUtils;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Service;
  10. import org.springframework.transaction.annotation.Transactional;
  11. import java.util.List;
  12. @Service
  13. public class DishServiceImpl implements DishService {
  14. @Autowired
  15. private DishMapper dishMapper;
  16. @Autowired
  17. private DishFlavorMapper dishFlavorMapper;
  18. /**
  19. * 新增菜品和对应的口味
  20. *
  21. * @param dishDTO
  22. */
  23. @Transactional //声明方法应该被包含在一个事务中执行
  24. public void saveWithFlavor(DishDTO dishDTO) {
  25. Dish dish = new Dish();
  26. BeanUtils.copyProperties(dishDTO, dish); //拷贝对象属性
  27. //向菜品表dish中插入1条数据
  28. dishMapper.insert(dish);
  29. //获取菜品的主键值
  30. Long dishId = dish.getId();
  31. List<DishFlavor> flavors = dishDTO.getFlavors();
  32. if (flavors != null && flavors.size() > 0) {
  33. //向口味表dish_flavor插入n条数据
  34. flavors.forEach(dishFlavor -> {
  35. dishFlavor.setDishId(dishId);
  36. });
  37. //批量插入口味数据
  38. dishFlavorMapper.insertBatch(flavors);
  39. }
  40. }
  41. }

DishMapper 中声明 insert 方法:

  1. /**
  2. * 插入菜品数据
  3. *
  4. * @param dish
  5. */
  6. @AutoFill(OperationType.INSERT)
  7. void insert(Dish dish);

新建 DishMapper.xml,在其中编写对应的 SQL

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  4. <mapper namespace="com.sky.mapper.DishMapper">
  5. <!--
  6. useGeneratedKeys="true": 表示获取数据插入后所在的主键值
  7. keyProperty="id": 表示将主键值赋给id属性
  8. -->
  9. <insert id="insert" useGeneratedKeys="true" keyProperty="id">
  10. insert into dish
  11. (name, category_id, price, image, description, status, create_time, update_time, create_user, update_user)
  12. values
  13. (#{name}, #{categoryId}, #{price}, #{image}, #{description}, #{status}, #{createTime}, #{updateTime}, #{createUser}, #{updateUser})
  14. </insert>
  15. </mapper>

新建 DishFlavorMapper,在其中声明 insertBatch 方法:

  1. import com.sky.entity.DishFlavor;
  2. import org.apache.ibatis.annotations.Mapper;
  3. import java.util.List;
  4. @Mapper
  5. public interface DishFlavorMapper {
  6. /**
  7. * 批量插入口味数据
  8. *
  9. * @param flavors
  10. */
  11. void insertBatch(List<DishFlavor> flavors);
  12. }

新建 DishFlavorMapper.xml,在其中编写对应的 SQL

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  4. <mapper namespace="com.sky.mapper.DishFlavorMapper">
  5. <insert id="insertBatch">
  6. insert into dish_flavor(dish_id, name, value) values
  7. <foreach collection="flavors" item="dishFlavor" separator=",">
  8. (#{dishFlavor.dishId}, #{dishFlavor.name}, #{dishFlavor.value})
  9. </foreach>
  10. </insert>
  11. </mapper>

功能测试

进行前后端联调测试,点击菜品管理,添加菜品,可以看到图片,说明文件上传接口开发成功:

在这里插入图片描述

填写一下其他信息,点击保存:

在这里插入图片描述

在这里插入图片描述

表中已经有了刚刚添加的数据,成功:

在这里插入图片描述

提交下代码到码云。

菜品分页查询

需求分析和设计

产品原型:

在这里插入图片描述

业务规则:

  • 根据页码展示菜品信息
  • 每页展示10条数据
  • 分页查询时可以根据需要输入菜品名称、菜品分类、菜品状态进行查询

接口设计:

在这里插入图片描述

代码开发

根据菜品分页查询接口定义设计对应的 DTO(项目中已开发):

在这里插入图片描述

由于返回数据多了一项分类名称,所以我们需要根据菜品分页查询接口定义设计对应的 VO 用于封装返回数据(项目中已开发):

在这里插入图片描述

根据接口定义创建 DishControllerpage 分页查询方法:

  1. /**
  2. * 菜品分页查询
  3. *
  4. * @param dishPageQueryDTO
  5. * @return
  6. */
  7. @GetMapping("/page")
  8. @ApiOperation("菜品分页查询")
  9. public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO) {
  10. log.info("菜品分页查询:{}", dishPageQueryDTO);
  11. PageResult pageResult = dishService.pageQuery(dishPageQueryDTO);
  12. return Result.success(pageResult);
  13. }

DishService 中扩展分页查询方法:

  1. /**
  2. * 菜品分页查询
  3. *
  4. * @param dishPageQueryDTO
  5. * @return
  6. */
  7. PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO);

DishServiceImpl 中实现分页查询方法:

  1. /**
  2. * 菜品分页查询
  3. *
  4. * @param dishPageQueryDTO
  5. * @return
  6. */
  7. public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
  8. PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
  9. Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
  10. return new PageResult(page.getTotal(), page.getResult());
  11. }

DishMapper 接口中声明 pageQuery 方法:

  1. /**
  2. * 菜品分页查询
  3. *
  4. * @param dishPageQueryDTO
  5. * @return
  6. */
  7. Page<DishVO> pageQuery(DishPageQueryDTO dishPageQueryDTO);

DishMapper.xml 中编写 SQL

  1. <select id="pageQuery" resultType="com.sky.vo.DishVO">
  2. select d.*, c.name as categoryName from dish d left join category c on d.category_id = c.id
  3. <where>
  4. <if test="name != null">
  5. and d.name like concat('%', #{
  6. name}, '%')
  7. </if>
  8. <if test="categoryId != null">
  9. and d.category_id = #{
  10. categoryId}
  11. </if>
  12. <if test="status != null">
  13. and d.status = #{
  14. status}
  15. </if>
  16. </where>
  17. order by d.create_time desc
  18. </select>

功能测试

进行前后端联调测试,可以看到所有菜品,也可以输入条件查询,可以切换下一页,成功:

没有显示图片是因为图片访问地址已失效,后面可以修改。

在这里插入图片描述

删除菜品

需求分析和设计

产品原型:

在这里插入图片描述

业务规则:

  • 可以一次删除一个菜品,也可以批量删除菜品
  • 起售中的菜品不能删除
  • 被套餐关联的菜品不能删除
  • 删除菜品后,关联的口味数据也需要删除掉

接口设计:

在这里插入图片描述

数据库设计:

在这里插入图片描述

代码开发

根据删除菜品的接口定义在 DishController 中创建方法:

  1. /**
  2. * 菜品批量删除
  3. *
  4. * @param ids
  5. * @return
  6. */
  7. @DeleteMapping
  8. @ApiOperation("菜品批量删除")
  9. public Result delete(@RequestParam List<Long> ids) {
  10. log.info("菜品批量删除:{}", ids);
  11. dishService.deleteBatch(ids);
  12. return Result.success();
  13. }

DishService 接口中声明 deleteBatch 方法:

  1. /**
  2. * 菜品批量删除
  3. *
  4. * @param ids
  5. */
  6. void deleteBatch(List<Long> ids);

DishServiceImpl 中实现 deleteBatch 方法:

  1. /**
  2. * 菜品批量删除
  3. *
  4. * @param ids
  5. */
  6. @Transactional
  7. public void deleteBatch(List<Long> ids) {
  8. ids.forEach(id -> {
  9. Dish dish = dishMapper.getById(id);
  10. //判断当前要删除的菜品状态是否为起售
  11. if (dish.getStatus() == StatusConstant.ENABLE) {
  12. //抛出自定义异常并返回错误信息给前端
  13. throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
  14. }
  15. });
  16. //判断当前要删除的菜品是否关联了套餐
  17. List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids); //根据菜品id查询关联的所有套餐id
  18. if (setmealIds != null && setmealIds.size() > 0) {
  19. throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
  20. }
  21. //删除菜品表中的数据
  22. ids.forEach(id -> {
  23. dishMapper.deleteById(id);
  24. //删除菜品对应的口味数据
  25. dishFlavorMapper.deleteByDishId(id);
  26. });
  27. }

DishMapper 中声明 getById 方法,并配置 SQL

  1. /**
  2. * 根据id查询菜品数据
  3. *
  4. * @param id
  5. * @return
  6. */
  7. @Select("select * from dish where id = #{id}")
  8. Dish getById(Long id);

创建 SetmealDishMapper,声明 getSetmealIdsByDishIds 方法,并在 xml 文件中编写 SQL

  1. import org.apache.ibatis.annotations.Mapper;
  2. import java.util.List;
  3. @Mapper
  4. public interface SetmealDishMapper {
  5. /**
  6. * 根据菜品id查询关联的套餐id
  7. *
  8. * @param ids
  9. * @return
  10. */
  11. List<Long> getSetmealIdsByDishIds(List<Long> ids);
  12. }
  13. <?xml version="1.0" encoding="UTF-8" ?>
  14. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  15. "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  16. <mapper namespace="com.sky.mapper.SetmealDishMapper">
  17. <select id="getSetmealIdsByDishIds" resultType="java.lang.Long">
  18. select setmeal_id from setmeal_dish where dish_id in
  19. <foreach collection="ids" separator="," open="(" close=")" item="dishId">
  20. #{dishId}
  21. </foreach>
  22. </select>
  23. </mapper>

DishMapper 中声明 deleteById 方法并配置 SQL

  1. /**
  2. * 根据id删除菜品
  3. *
  4. * @param id
  5. */
  6. @Delete("delete from dish where id = #{id}")
  7. void deleteById(Long id);

DishFlavorMapper 中声明 deleteByDishId 方法并配置 SQL

  1. /**
  2. * 根据菜品id删除口味数据
  3. *
  4. * @param dishId
  5. */
  6. @Delete("delete from dish_flavor where dish_id = #{dishId}")
  7. void deleteByDishId(Long dishId);

代码优化

  1. //删除菜品表中的数据
  2. ids.forEach(id -> {
  3. dishMapper.deleteById(id);
  4. //删除菜品对应的口味数据
  5. dishFlavorMapper.deleteByDishId(id);
  6. });

我们可以把 deleteBatch 的最后几行代码优化一下,原本的代码是遍历菜品 id 集合,然后一个一个去删除菜品和对应的口味数据,当数据量非常大时,SQL 语句就会非常多,会影响我们系统的效率,所以我们将其改进一下。

  1. //改进:直接根据菜品id集合一次性删除菜品, 减少SQL语句
  2. dishMapper.deleteByIds(ids);
  3. //根据菜品id集合一次性删除关联的口味数据
  4. dishFlavorMapper.deleteByDishIds(ids);

DishMapper.xmlSQL 语句:

  1. <delete id="deleteByIds">
  2. delete from dish where id in
  3. <foreach collection="ids" separator="," open="(" close=")" item="id">
  4. #{id}
  5. </foreach>
  6. </delete>

DishFlavorMapper.xmlSQL 语句:

  1. <delete id="deleteByDishIds">
  2. delete from dish_flavor where dish_id in
  3. <foreach collection="dishIds" separator="," open="(" close=")" item="dishId">
  4. #{dishId}
  5. </foreach>
  6. </delete>

功能测试

通过Swagger接口文档进行测试,通过后再前后端联调测试即可

修改菜品

需求分析和设计

产品原型:

在这里插入图片描述

接口设计:

  • 根据id查询菜品

    在这里插入图片描述

  • 根据类型查询分类(已实现)
  • 文件上传(已实现)
  • 修改菜品

    在这里插入图片描述

代码开发

根据 id 查询菜品接口开发

DishController 中创建 getById 方法:

  1. /**
  2. * 根据id查询菜品和关联的口味数据
  3. *
  4. * @param id
  5. * @return
  6. */
  7. @GetMapping("/{id}")
  8. @ApiOperation("根据id查询菜品和关联的口味数据")
  9. public Result<DishVO> getById(@PathVariable Long id) {
  10. log.info("根据id查询菜品和关联的口味数据:{}", id);
  11. return Result.success(dishService.getByIdWithFlavor(id));
  12. }

DishService 接口中声明 getByIdWithFlavor 方法:

  1. /**
  2. * 根据id查询菜品和关联的口味数据
  3. *
  4. * @param id
  5. * @return
  6. */
  7. DishVO getByIdWithFlavor(Long id);

DishServiceImpl 中实现 getByIdWithFlavor 方法:

  1. /**
  2. * 根据id查询菜品和关联的口味数据
  3. *
  4. * @param id
  5. * @return
  6. */
  7. public DishVO getByIdWithFlavor(Long id) {
  8. //查询菜品表
  9. Dish dish = dishMapper.getById(id);
  10. //查询菜品关联的口味
  11. List<DishFlavor> dishFlavorList = dishFlavorMapper.getByDishId(id);
  12. //封装成VO
  13. DishVO dishVO = new DishVO();
  14. BeanUtils.copyProperties(dish, dishVO);
  15. dishVO.setFlavors(dishFlavorList);
  16. return dishVO;
  17. }

DishFlavorMapper 中声明 getByDishId 方法,并配置 SQL

  1. /**
  2. * 根据菜品id查询对应的口味
  3. *
  4. * @param dishId
  5. * @return
  6. */
  7. @Select("select * from dish_flavor where dish_id = #{dishId}")
  8. List<DishFlavor> getByDishId(Long dishId);

修改菜品接口开发

DishController 中创建 update 方法:

  1. /**
  2. * 修改菜品
  3. *
  4. * @param dishDTO
  5. * @return
  6. */
  7. @PutMapping
  8. @ApiOperation("修改菜品")
  9. public Result update(@RequestBody DishDTO dishDTO) {
  10. log.info("修改菜品:{}", dishDTO);
  11. dishService.updateWithFlavor(dishDTO);
  12. return Result.success();
  13. }

DishService 接口中声明 updateWithFlavor 方法:

  1. /**
  2. * 根据id修改菜品和关联的口味
  3. * @param dishDTO
  4. */
  5. void updateWithFlavor(DishDTO dishDTO);

DishServiceImpl 中实现 updateWithFlavor 方法:

  1. /**
  2. * 根据id修改菜品和关联的口味
  3. *
  4. * @param dishDTO
  5. */
  6. @Transactional
  7. public void updateWithFlavor(DishDTO dishDTO) {
  8. Dish dish = new Dish();
  9. BeanUtils.copyProperties(dishDTO, dish);
  10. //获取所要修改菜品的id
  11. Long dishId = dishDTO.getId();
  12. //修改菜品表dish
  13. dishMapper.update(dish);
  14. //删除当前菜品关联的口味数据
  15. dishFlavorMapper.deleteByDishId(dishId);
  16. //插入最新的口味数据
  17. List<DishFlavor> flavors = dishDTO.getFlavors();
  18. if (flavors != null && flavors.size() > 0) {
  19. flavors.forEach(dishFlavor -> {
  20. dishFlavor.setDishId(dishId);
  21. });
  22. //批量插入口味数据
  23. dishFlavorMapper.insertBatch(flavors);
  24. }
  25. }

DishMapper 中声明 update 方法:

  1. /**
  2. * 根据菜品id修改菜品信息
  3. *
  4. * @param dish
  5. */
  6. @AutoFill(OperationType.UPDATE)
  7. void update(Dish dish);

DishMapper.xml 中配置 SQL

  1. <!-- 根据菜品id修改菜品信息-->
  2. <update id="update">
  3. update dish
  4. <set>
  5. <if test="name != null">
  6. name = #{name},
  7. </if>
  8. <if test="categoryId != null">
  9. category_id = #{categoryId},
  10. </if>
  11. <if test="price != null">
  12. price = #{price},
  13. </if>
  14. <if test="image != null">
  15. image = #{image},
  16. </if>
  17. <if test="description != null">
  18. description = #{description},
  19. </if>
  20. <if test="status != null">
  21. status = #{status},
  22. </if>
  23. <if test="updateTime != null">
  24. update_time = #{updateTime},
  25. </if>
  26. <if test="updateUser != null">
  27. update_user = #{updateUser}
  28. </if>
  29. </set>
  30. where id = #{id}
  31. </update>

功能测试

直接进行前后端联调比较方便,可以给没有图片的菜品修改图片:

在这里插入图片描述

菜品启售停售

需求分析和设计

产品原型:

在这里插入图片描述

业务规则:

  • 菜品停售,则包含菜品的套餐同时停售

接口设计:

在这里插入图片描述

数据库设计:

涉及 dishsetmealsetmeal_dish 三个表

代码开发

DishController 中创建 startOrStop 方法:

  1. /**
  2. * 菜品启售停售
  3. *
  4. * @param status
  5. * @return
  6. */
  7. @PostMapping("/status/{status}")
  8. @ApiOperation("菜品启售停售")
  9. public Result startOrStop(@PathVariable Integer status, Long id) {
  10. log.info("菜品启售停售:{}", status);
  11. dishService.startOrStop(status, id);
  12. return Result.success();
  13. }

DishService 中声明 startOrStop 方法:

  1. /**
  2. * 修改菜品状态
  3. *
  4. * @param status
  5. * @param id
  6. */
  7. void startOrStop(Integer status, Long id);

DishServiceImpl 中实现 startOrStop 方法:

  1. /**
  2. * 修改菜品状态
  3. *
  4. * @param status
  5. * @param id
  6. */
  7. @Transactional //涉及修改的操作加入事务管理比较好
  8. public void startOrStop(Integer status, Long id) {
  9. Dish dish = dishMapper.getById(id);//获取菜品对象
  10. dish.setStatus(status);//设置菜品状态
  11. dishMapper.update(dish);//更新菜品信息
  12. //如果是停售操作, 则需要将菜品关联的套餐一并停售
  13. if (status.equals(StatusConstant.DISABLE)) {
  14. List<Long> dishIds = new ArrayList<>();
  15. dishIds.add(id);
  16. //根据菜品id查询关联的所有套餐id
  17. List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
  18. if (setmealIds != null && setmealIds.size() > 0) {
  19. setmealIds.forEach(setmealId -> {
  20. Setmeal setmeal = Setmeal.builder()
  21. .id(setmealId)
  22. .status(StatusConstant.DISABLE)
  23. .build();
  24. setmealMapper.update(setmeal); //根据套餐id修改套餐信息
  25. });
  26. }
  27. }
  28. }

SetmealMapper 中声明 update 方法:

  1. /**
  2. * 根据套餐id修改套餐信息
  3. *
  4. * @param setmeal
  5. */
  6. @AutoFill(OperationType.UPDATE)
  7. void update(Setmeal setmeal);

新建 SetmealMapper.xml,并在其中配置对应的 SQL

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  4. <mapper namespace="com.sky.mapper.SetmealMapper">
  5. <!-- 根据套餐id修改套餐信息-->
  6. <update id="update">
  7. update setmeal
  8. <set>
  9. <if test="categoryId != null">
  10. category_id = #{
  11. categoryId},
  12. </if>
  13. <if test="name != null">
  14. name = #{
  15. name},
  16. </if>
  17. <if test="price != null">
  18. price = #{
  19. price},
  20. </if>
  21. <if test="status != null">
  22. status = #{
  23. status},
  24. </if>
  25. <if test="description != null">
  26. description = #{
  27. description},
  28. </if>
  29. <if test="image != null">
  30. image = #{
  31. image},
  32. </if>
  33. <if test="updateTime != null">
  34. update_time = #{
  35. updateTime},
  36. </if>
  37. <if test="updateUser != null">
  38. update_user = #{
  39. updateUser}
  40. </if>
  41. </set>
  42. where id = #{
  43. id}
  44. </update>
  45. </mapper>

功能测试

通过swagger接口文档和前后端联调进行功能测试

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,131人围观)

还没有评论,来说两句吧...

相关阅读

    相关 苍穹——项目搭建

    本项目(苍穹外卖)是专门为餐饮企业(餐厅、饭店)定制的一款软件产品,包括 系统管理后台 和 小程序端应用 两部分。其中系统管理后台主要提供给餐饮企业内部员工使用,可以对餐...