苍穹外卖学习笔记(五)

文章目录

二.新增菜品

1.图片上传

这里采用了阿里云oss对象存储服务

  1. application.yml
yml 复制代码
  alioss:
    endpoint: ${sky.alioss.endpoint}
    access-key-id: ${sky.alioss.access-key-id}
    access-key-secret: ${sky.alioss.access-key-secret}
    bucket-name: ${sky.alioss.bucket-name}
  1. OssConfiguration 用来初始化,具体的配置文件在common中properties中
java 复制代码
package com.sky.config;

import com.sky.properties.AliOssProperties;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 阿里云OSS配置
 */
@Configuration
@Slf4j
public class OssConfiguration {

    @Bean
    @ConditionalOnMissingBean//当容器里没有指定的Bean的情况下创建该对象
    public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties) {
        log.info("初始化阿里云OSS配置");
        return new AliOssUtil(aliOssProperties.getEndpoint(),
                              aliOssProperties.getAccessKeyId(),
                              aliOssProperties.getAccessKeySecret(),
                              aliOssProperties.getBucketName());
    }
}
  1. CommonController.java
java 复制代码
package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Api(tags = "通用接口")
@RestController
@RequestMapping("/admin/common")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传:{}", file);
        try {
            String originalFilename = file.getOriginalFilename();
            //截取文件后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString() + suffix;
            String url = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(url);
        } catch (IOException e) {
            log.error("文件上传失败: {}", e.getMessage(), e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}

2.具体新增菜品

  1. DishController
java 复制代码
package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.result.Result;
import com.sky.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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
@RequestMapping("/admin/dish")
@Slf4j
@Api(tags = "菜品管理")
public class DishController {

    @Autowired
    private DishService dishService;

    /**
     * 新增菜品
     */
    @PostMapping
    @ApiOperation("新增菜品")
    public Result save(@RequestBody DishDTO dishDTO) {
        log.info("新增菜品:{}", dishDTO);
        dishService.saveWithFlavor(dishDTO);
        return Result.success();
    }
}
  1. DishService
java 复制代码
public interface DishService {

    /**
     * 新增菜品和口味
     */
    void saveWithFlavor(DishDTO dishDTO);
}
  1. DishServiceImpl
java 复制代码
package com.sky.service.impl;

import com.baomidou.mybatisplus.core.batch.MybatisBatch;
import com.sky.dto.DishDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
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.Arrays;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 新增菜品和口味
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        //向菜品表插入一条数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);
        dishMapper.selectById(dish.getId()); // 获取插入后的主键值
        //获取菜品id
        Long dishId = dish.getId();
        //向口味表插入多条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            // 设置 dishId
            flavors.forEach(flavor -> flavor.setDishId(dishId));
            // 批量插入
            MybatisBatch<DishFlavor> mybatisBatch = new MybatisBatch<>(sqlSessionFactory, flavors);
            MybatisBatch.Method<DishFlavor> method = new MybatisBatch.Method<>(DishFlavorMapper.class);
            mybatisBatch.execute(method.insert());
        }
    }
}
  1. DishMapper
java 复制代码
@Mapper
public interface DishMapper extends BaseMapper<Dish> {
}
  1. DishFlavorMapper
java 复制代码
@Mapper
public interface DishFlavorMapper extends BaseMapper<DishFlavor> {

}
  1. 注意需要在实体类中添加主键自增策略,也可以配置主键全局自增,如果还是默认的雪花算法,需要把数据库重建
yml 复制代码
# mybatis-plus配置
mybatis-plus:
  configuration:
    # 驼峰命名
    map-underscore-to-camel-case: true
    # 日志
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      id-type: auto
相关推荐
2401_8574396912 分钟前
SpringBoot框架在资产管理中的应用
java·spring boot·后端
怀旧66613 分钟前
spring boot 项目配置https服务
java·spring boot·后端·学习·个人开发·1024程序员节
李老头探索15 分钟前
Java面试之Java中实现多线程有几种方法
java·开发语言·面试
芒果披萨21 分钟前
Filter和Listener
java·filter
qq_49244844625 分钟前
Java实现App自动化(Appium Demo)
java
阿华的代码王国34 分钟前
【SpringMVC】——Cookie和Session机制
java·后端·spring·cookie·session·会话
infiniteWei1 小时前
【Lucene】原理学习路线
学习·搜索引擎·全文检索·lucene
找了一圈尾巴1 小时前
前后端交互通用排序策略
java·交互
follycat1 小时前
[极客大挑战 2019]PHP 1
开发语言·学习·网络安全·php
weixin_518285053 小时前
深度学习笔记11-神经网络
笔记·深度学习·神经网络