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;//菜品分类idprivate 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;@TableLogicprivate 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;@TableLogicprivate 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 {@Autowiredprivate DishFlavorService dishFlavorService;/*** 新增菜品** @param dishDto*/@Override@Transactionalpublic 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 {@Autowiredprivate DishService dishService;@Autowiredprivate 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();//分类idCategory 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*/@Overridepublic 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.批量删除
@DeleteMappingpublic R<String> delete(String ids) {String[] split = ids.split(","); //将每个id分开//每个id还是字符串,转成LongList<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 转成LongString[] 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("操作成功");}