瑞吉外卖Day04

小张推荐:瑞吉外卖Day03   ,   瑞吉外卖Day05

1.文件的上传下载

瑞吉外卖Day04_第1张图片

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

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R 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);
    }

瑞吉外卖Day04_第2张图片

  /**
     * 文件下载
     */
    @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 category){

        //条件构造器
        LambdaQueryWrapper queryWrapper=new LambdaQueryWrapper();
        //条件
        queryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        //排序条件
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List 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 flavors=new ArrayList<>();

    private String categoryName;

    private Integer copies;
}

2.3service层

public interface DishService extends IService {
    //新增菜品,同时插入菜品对应的口味
    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 implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;


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

        Long dishId = dishDto.getId();

        //保存菜品口味
        List 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 save(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);

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

}

3.菜品分页查询

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

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

        dishService.page(pageInfo, queryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List records = pageInfo.getRecords();
        List 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 queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List flavors = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(flavors);
        return dishDto;

    }

回显查询

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

5.批量删除

    @DeleteMapping
    public R delete(String ids) {
        String[] split = ids.split(","); //将每个id分开
        //每个id还是字符串,转成Long
        List 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 setStatus(@PathVariable int st, String ids) {
        //处理string 转成Long
        String[] split = ids.split(",");
        List idList = Arrays.stream(split).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());

        //将每个id new出来一个Dish对象,并设置状态
        List 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("操作成功");
    }

你可能感兴趣的:(瑞吉外卖,java,前端,开发语言,spring,spring,boot,后端)