学习日记 2022.11.13

1.展示菜品口味信息

把查询菜品返回dish集合封装为dishDto

/**
     * 根据条件查询菜品数据
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        log.info("根据条件查询菜品数据: {}", dish.toString());
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //根据id查询
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //查询状态为起售的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        //排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            //select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }

前端接收到数据之后就会展示口味信息

2.展示套餐信息

/**
     * 根据id查询套餐
     *
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setMealService.list(queryWrapper);
        return R.success(list);
    }

3.购物车开发

/**
     * 添加套餐或菜品到购物车
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        log.info("添加套餐或菜品到购物车: {}", shoppingCart.toString());
        // 设置用户id
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        // 查询用户套餐或菜品是否已存在
        if (shoppingCart.getDishId() != null) {
            //添加的是菜品
            queryWrapper.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
        } else {
            //添加的是套餐
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }

        ShoppingCart shoppingCartServiceOne = shoppingCartService.getOne(queryWrapper);
        if (shoppingCartServiceOne != null) {
            // 已存在则修改该套餐或菜品number+1
            Integer number = shoppingCartServiceOne.getNumber();
            shoppingCartServiceOne.setNumber(number + 1);
            shoppingCartService.updateById(shoppingCartServiceOne);
        }else {
            // 不存在则添加到购物车中
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            shoppingCartServiceOne = shoppingCart;
        }
        return R.success(shoppingCartServiceOne);
    }

    /**
     * 查看购物车列表
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list() {
        log.info("查看购物车清单");
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        queryWrapper.orderByDesc(ShoppingCart::getCreateTime);

        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        return R.success(list);
    }

    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> clean(){
        log.info("清空购物车");
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        shoppingCartService.remove(queryWrapper);
        return R.success("清空购物车成功");
    }

4.提交订单

/**
     * 提交订单
     * @param orders
     */
    @Override
    public void submit(Orders orders) {
        // 获取用户id
        Long userId = BaseContext.getCurrentId();

        // 查询购物车
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> list = shoppingCartService.list(wrapper);

        if(list == null||list.size()==0){
            throw new BusinessException("购物车为空,不能下单");
        }

        // 插入订单表 一条数据(需要先查询手机号和默认地址)
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        User user = userService.getById(userId);
        if(addressBook == null){
            throw new BusinessException("地址信息有误,无法下单");
        }

        long orderId = IdWorker.getId();
        //使用stream流计算购物车总金额
        AtomicInteger amount = new AtomicInteger(0);
        List<OrderDetail> orderDetails = list.stream().map((item)->{
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());


        orders.setId(orderId);//设置订单号
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表插入数据,一条数据
        this.save(orders);

        // 插入订单明细表 可能多条数据
        orderDetailService.saveBatch(orderDetails);

        // 清空购物车数据
        shoppingCartService.remove(wrapper);
    }

5.stream流后半部分学习

        //Stream流map映射  a->A
        List<String> list = Arrays.asList("aa", "bb", "cc", "dd");
        list.stream().map(str -> str.toUpperCase()).forEach(System.out::print);

        ArrayList list1 = new ArrayList();
        list1.add(1);
        list1.add(2);
        list1.add(3);
        ArrayList list2 = new ArrayList();
        list2.add(4);
        list2.add(5);
        list2.add(6);

        //platmap映射相当于把集合每个元素当成一个流
        /*list1.add(list2);
        System.out.println(list1);*/
        //map映射相当于把集合每个元素打散汇成一个大的流
        /*list1.addAll(list2);
        System.out.println(list1);*/

        //排序
        //1.自然排序
        List<Integer> list3 = Arrays.asList(10, 45, 2, 3, 455);
        list3.stream().sorted().forEach(System.out::println);
        //2.定制排序
        list3.stream().sorted((num1,num2)->Integer.compare(num2,num1)).forEach(System.out::println);

        /**
         * stream流终止操作
         * 1.匹配与查找
         */
        List<User> userList = new ArrayList<>();
        userList.add(new User("zs",18,"BJ"));
        userList.add(new User("ls",23,"SH"));
        userList.add(new User("wu",45,"SC"));
        userList.add(new User("sq",36,"JS"));
        userList.add(new User("zb",19,"ZJ"));
        userList.add(new User("nn",44,"HB"));
        //allMatch()是否全匹配返回布尔值
        boolean b = userList.stream().allMatch(user -> user.getAge() > 10);
        System.out.println(b);
        //anyMatch()任一匹配
        boolean b1 = userList.stream().anyMatch(user -> user.getAge() > 40);
        System.out.println(b1);
        //anyMatch()无一匹配
        boolean b2 = userList.stream().noneMatch(user -> user.getAge() > 50);
        System.out.println(b2);
        //findFirst()返回第一个
        Optional<User> user = userList.stream().findFirst();
        System.out.println(user);
        //findFirst()返回第任一
        Optional<User> user1 = userList.stream().findAny();
        System.out.println(user1);

        //max,min,count类似sql
        long count = userList.stream().filter(u -> u.getAge() > 18).count();
        System.out.println(count);
        Optional<Integer> max = userList.stream().map(u -> u.getAge()).max(Integer::compare);
        System.out.println(max);
        Optional<Integer> min = userList.stream().map(u -> u.getAge()).min(Integer::compare);
        System.out.println(min);

        //forEach内部迭代
        list1.stream().forEach(System.out::println);

运行结果:

AABBCCDD2
3
10
45
455
455
45
10
3
2
true
true
true
Optional[User{name='zs', age=18, address='BJ'}]
Optional[User{name='zs', age=18, address='BJ'}]
5
Optional[45]
Optional[18]
1
2
3

/**
         * stream终止操作
         * 2.归约reduce
         */
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        //reduce方法需要三个参数,最前面的是初始值  计算1~10的和
        Integer reduce = list.stream().reduce(0, Integer::sum);
        System.out.println(reduce);

        List<User> userList = new ArrayList<>();
        userList.add(new User("zs",18,"BJ"));
        userList.add(new User("ls",23,"SH"));
        userList.add(new User("wu",45,"SC"));
        userList.add(new User("sq",36,"JS"));
        userList.add(new User("zb",19,"ZJ"));
        userList.add(new User("nn",44,"HB"));
        //计算年龄总和
        Optional<Integer> ageSum = userList.stream().map(User::getAge).reduce(Integer::sum);
        System.out.println(ageSum);

        /**
         * stream终止操作
         * 3.收集collect()
         * Collectors静态方法
         */
        //查找年龄大于30的用户,收集到一个list集合中(set)
        List<User> users = userList.stream().filter(user -> user.getAge() > 30).collect(Collectors.toList());
        System.out.println(users);

运行结果: 

55
Optional[185]
[User{name='wu', age=45, address='SC'}, User{name='sq', age=36, address='JS'}, User{name='nn', age=44, address='HB'}]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值