瑞吉外卖Day04

news2024/10/6 5:25:28

1.文件的上传下载

  @Value("${reggie.path}")
    private String basePath;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info("文件上传");

        //原始文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用uuid重新生成文件名,防止文件被覆盖
        String filename = UUID.randomUUID().toString() + suffix;

        //创建目录对象
        File dir = new File(basePath);
        if (!dir.exists()) {//目录不存在创建
            dir.mkdir();
        }

        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(basePath + filename));
        } catch (IOException e) {
            e.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");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } 

 2.新增菜品

2.1分类

   /**
     * 根据条件查询分类数据
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){

        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper();
        //条件
        queryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        //排序条件
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);

    }

2.2创建实体类

@Data
public class Dish {

    private Long id;
    //菜品名称
    private String name;

    //菜品分类id
    private Long categoryId;

    //菜品价格
    private BigDecimal price;
    //商品码
    private String code;

    //商品图片
    private String image;
    //描述信息
    private String description;
    //状态
    private Integer status;
    //顺序
    private Integer sort;

    @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;
    @TableLogic
    private Integer is_deleted;
}
@Data
public class DishFlavor implements Serializable {
    private Long id;

    private Long dishId;

    private String name;

    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;
    @TableLogic
    private Integer is_deleted;

}

dto

@Data
public class DishDto extends Dish {

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

    private String categoryName;

    private Integer copies;
}

2.3service层

public interface DishService extends IService<Dish> {
    //新增菜品,同时插入菜品对应的口味
    public void saveWithFlavor(DishDto dishDto);
}

因为添加了@Transactional事务注解,所以主程序上添加事务驱动注解:

@Slf4j
@SpringBootApplication
@ServletComponentScan
@EnableTransactionManagement
public class ProductRuijiApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProductRuijiApplication.class, args);
        log.info("程序启动成功");
    }
}

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

    @Autowired
    private DishFlavorService dishFlavorService;


    /**
     * 新增菜品
     *
     * @param dishDto
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品的基本信息
        this.save(dishDto);

        Long dishId = dishDto.getId();

        //保存菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map(item -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);

    }
}

2.4controller层

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @PostMapping()
    public R<String> save(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);

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

}

3.菜品分页查询

  @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(pageInfo, queryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //拷贝
            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            Category category = categoryService.getById(categoryId);
            if (category!=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

4.修改菜品

4.1页面回显

因为需要查两张表,所以自定义查询

/**
     * 根据id查询菜品信息,以及口味信息
     *
     * @param id
     */
    @Override
    public DishDto getWithFlavor(Long id) {
        //1.菜品基本信息
        Dish dish = this.getById(id);

        DishDto dishDto=new DishDto();
        BeanUtils.copyProperties(dish,dishDto);

        //2.菜品对应的口味信息
        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(flavors);
        return dishDto;

    }

回显查询

 /**
     * 根据id查询菜品id
     */
    @GetMapping ("/{id}")
    public R<DishDto> get(@PathVariable("id") Long id){
        DishDto dishDto = dishService.getWithFlavor(id);
        return R.success(dishDto);
    }

5.批量删除

    @DeleteMapping
    public R<String> delete(String ids) {
        String[] split = ids.split(","); //将每个id分开
        //每个id还是字符串,转成Long
        List<Long> idList = Arrays.stream(split).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        dishService.removeByIds(idList);//执行批量删除
        log.info("删除的ids: {}", ids);
        return R.success("删除成功"); //返回成功
    }

6.起售与禁售

@PostMapping("/status/{st}")
    public R<String> setStatus(@PathVariable int st, String ids) {
        //处理string 转成Long
        String[] split = ids.split(",");
        List<Long> idList = Arrays.stream(split).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());

        //将每个id new出来一个Dish对象,并设置状态
        List<Dish> dishes = idList.stream().map((item) -> {
            Dish dish = new Dish();
            dish.setId(item);
            dish.setStatus(st);
            return dish;
        }).collect(Collectors.toList()); //Dish集合

        log.info("status ids : {}", ids);
        dishService.updateBatchById(dishes);//批量操作
        return R.success("操作成功");
    }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1211834.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

22款奔驰E260L升级原厂360全景影像 高清环绕的视野

360全景影像影像系统提升行车时的便利&#xff0c;不管是新手或是老司机都将是一个不错的配置&#xff0c;无论是在倒车&#xff0c;挪车以及拐弯转角的时候都能及时关注车辆所处的环境状况&#xff0c;避免盲区事故发生&#xff0c;提升行车出入安全性。 360全景影像包含&…

基于安卓android微信小程序的师生答疑交流平app

项目介绍 本课题研究的是基于HBuilder X系统平台的师生答疑交流APP&#xff0c;开发这款师生答疑交流APP主要是为了帮助用户可以不用约束时间与地点进行所需信息。本文详细讲述了师生答疑交流APP的界面设计及使用&#xff0c;主要包括界面的实现、控件的使用、界面的布局和异常…

macOS btop

brew install btop参考 5 个 htop 替代&#xff1a;增强你的 Linux 系统监控体验btop github

Git本地项目提交到Gitee的操作流程

一、Gitee创建一个仓库 第一步&#xff1a; 第二步&#xff1a; 第三步&#xff1a; 第四步&#xff1a;复制该仓库地址&#xff08;https://gitee.com/yassels/test_1115.git&#xff09;&#xff0c;留待后续使用 二、操作本地文件上传到Gitee 第一步&#xff1a; 第二步…

[NSSRound#7 Team]ShadowFlag

文章目录 前置知识/proc目录python的反弹shellpin码计算 解题步骤 前置知识 /proc目录 Linux系统上的/proc目录是一种文件系统&#xff0c;用户可以通过这些文件查看有关系统硬件及当前正在运行进程的信息&#xff0c;甚至可以通过更改其中某些文件来改变内核的运行状态。/pro…

Spring全家桶源码解析--2.2 Spring bean 的创建

文章目录 前言一、Bean 的生成过程&#xff1a;1.1 创建过程&#xff1a;1.1.1 doGetBean 创建bean1.1.2 单例bean 创建getSingleton&#xff1a;1.1.3 单例bean 创建createBean&#xff1a;1.1.4 单例bean 创建doCreateBean&#xff1a;1.1.5 bean 实例化和初始化之后factoryB…

PostGIS学习教程六:几何图形(geometry)

文章目录 一、介绍二、元数据表三、表示真实世界的对象3.1、点&#xff08;Points&#xff09;3.2、线串&#xff08;Linestring&#xff09;3.3、多边形&#xff08;Polygon&#xff09;3.4、图形集合&#xff08;Collection&#xff09; 四、几何图形输入和输出五、从文本转换…

Mysql中的索引与事务和B树的知识补充

索引与事务和B树的知识补充 一.索引1.概念2.作用3.使用场景4.使用 二.事务1.为什么使用事务2.事务的概念3.使用3.1脏读问题3.2不可重复读3.3 幻读问题3.4解决3.5 使用代码 三.B树的知识补充1.B树2.B树 一.索引 1.概念 索引是一种特殊的文件&#xff0c;包含着对数据表里所有记…

C++基础知识记录

github仓库不定期更新: https://github.com/han-0111/CppLearning 文章目录 C如何工作编译器和链接器编译器预处理(Preprocessing)includedefineif/endif 链接器一种比较复杂的情况 变量变量类型intcharshortlonglong longfloatdoublebool如何查看数据大小 函数头文件条件语句…

使用 sCrypt CLI 工具验证合约

通过向 Whatsonchain 提交合约源代码可以实现合约的验证。 另外一种方法是使用 sCrypt CLI 工具来验证合约。 You can verify the deployed smart contracts script using the verify command: scrypt verify <scriptHash> <contractPath>第一个位置参数是已部署…

博客系统页面设计

目录 前言 1.预期效果 1.1博客列表页效果 1.2博客详情页效果 1.3博客登陆页效果 2.实现博客列表页 2.1实现导航栏 2.2实现版心 2.3实现个人信息 2.4实现博客列表 3.实现博客正文页 3.1引入导航栏 3.2引入版心 3.3引入个人信息 3.4实现博客正文 4.实现博客登陆页…

javascript原来还可以这样比较两个日期(直接使用new Date)

有个需求是这样的&#xff1a;假设今天是2023/11/15 有一个表格&#xff0c;表格中操作列按钮的展示与隐藏依靠开始结束日期来进行展示&#xff0c;如果当前日期在开始结束日期之间&#xff0c;则进行展示&#xff0c;我一开始做的时候使用new Date转换成时间戳(getTime)进行比…

7天入门python系列之爬取热门小说项目实战,互联网的东西怎么算白嫖呢

第七天 Python项目实操 编者打算开一个python 初学主题的系列文章&#xff0c;用于指导想要学习python的同学。关于文章有任何疑问都可以私信作者。对于初学者想在7天内入门Python&#xff0c;这是一个紧凑的学习计划。但并不是不可完成的。 学到第7天说明你已经对python有了一…

生活消费分销系统搭建开发制作

文章目录 前言 一、生活消费系统是什么&#xff1f;二、生活消费分销系统的营销方式和功能三、总结 一、生活消费系统介绍 生活消费系统涵盖了吃喝玩乐&#xff0c;衣食住行。网购消费等生活消费的优惠券领取以及分销功能 二、生活消费分销系统的营销方式和功能 A: 会员体…

基于Springboot的影城管理系统(有报告)。Javaee项目,springboot项目。

演示视频&#xff1a; 基于Springboot的影城管理系统&#xff08;有报告&#xff09;。Javaee项目&#xff0c;springboot项目。 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到网站。 项目介绍…

【Proteus仿真】【Arduino单片机】DS18B20温度计

文章目录 一、功能简介二、软件设计三、实验现象联系作者 一、功能简介 本项目使用Proteus8仿真Arduino单片机控制器&#xff0c;使用PCF8574、LCD1602液晶、DS18B20温度传感器等。 主要功能&#xff1a; 系统运行后&#xff0c;LCD1602显示传感器采集温度。 二、软件设计 /*…

Android抓包工具—Fiddler详解

前言 平时和其他大佬交流时&#xff0c;总会出现这么些话&#xff0c;“抓个包看看就知道哪出问题了”&#xff0c;“抓流量啊&#xff0c;payload都在里面”&#xff0c;“这数据流怎么这么奇怪”。 &#x1f449;这里出现的名词&#xff0c;其实都是差不多的意思啊&#xf…

leetcode:1576. 替换所有的问号(python3解法)

难度&#xff1a;简单 给你一个仅包含小写英文字母和 ? 字符的字符串 s&#xff0c;请你将所有的 ? 转换为若干小写字母&#xff0c;使最终的字符串不包含任何 连续重复 的字符。 注意&#xff1a;你 不能 修改非 ? 字符。 题目测试用例保证 除 ? 字符 之外&#xff0c;不存…

Unity反编译:IL2CPP 打包输出的cpp文件和dll(程序集)位置、Mono打包输出的dll(程序集)位置

目录 如题&#xff1a;IL2CPP 打包输出的cpp文件和dll位置(并不会出现在APK里) 如题&#xff1a;Mono打包输出的dll位置 校验平台&#xff1a;Android 如题&#xff1a;IL2CPP 打包输出的cpp文件和dll位置(并不会出现在APK里) Unity Assets同级目录下 Temp/StagingArea/Il2…

C# datagridView 控件使用心得

首先本人的需求是&#xff0c;通过UI编辑一个表格文件&#xff0c;然后将其存储起来。 同时也可以对其进行载入,话不多说先上图片 dataGridView1 的初始化&#xff0c;这个控件的初始化可以使用UI界面的设置&#xff0c;也可以使用程序&#xff1a; Column1 new System.Window…