前言

谷粒商城的基础部分3/3

全笔记链接(链接给出)

谷粒商城笔记(详细版) IDEA2021 基础篇(1/3).

谷粒商城笔记(详细版) IDEA2021 基础篇(2/3).

ES6 VUE 基础篇前端笔记

谷粒商城笔记(详细版) IDEA2021 基础篇(3/3).


正式部分

29 平台属性-规格参数新增与VO

1 VO简介

在这里插入图片描述
VO viewobject 就是接受页面传来的数据 封装对象
或者将业务处理完成的对象封装成页面要用的数据

2 问题所在

在这里插入图片描述
在这里插入图片描述
我们前端在新增规格参数时还没有把传来的groupid
传到属性 分组 realation表当中
现在我们来进行代码编写
我们首先来到attr实体类
发现里面没有Groupid字段
在这里插入图片描述
如果新增一个字段并加上 @TableField(exist = false)
会和数据库不对应 并且很不规范

3解决方案

创建一个attrVo来接受前端传来数据
其中新建一个属性
因为其不和数据库绑定 所以不用加很多数据库注解

package com.atguigu.gulimall.product.vo;


import lombok.Data;

@Data
public class AttrVo {
    /**
     * 属性id
     */
    private Long attrId;
    /**
     * 属性名
     */
    private String attrName;
    /**
     * 是否需要检索[0-不需要,1-需要]
     */
    private Integer searchType;
    /**
     * 值类型[0-为单个值,1-可以选择多个值]
     */
    private Integer valueType;
    /**
     * 属性图标
     */
    private String icon;
    /**
     * 可选值列表[用逗号分隔]
     */
    private String valueSelect;
    /**
     * 属性类型[0-销售属性,1-基本属性,2-既是销售属性又是基本属性]
     */
    private Integer attrType;
    /**
     * 启用状态[0 - 禁用,1 - 启用]
     */
    private Long enable;
    /**
     * 所属分类
     */
    private Long catelogId;
    /**
     * 快速展示【是否展示在介绍上;0-否 1-是】,在sku中仍然可以调整
     */
    private Integer showDesc;

    private Long attrGroupId;
}

我们的attr实体类属性就和数据库进行对应 不再进行更改

1 controller编写接受vo

    /**
     * 保存
     */
    @RequestMapping("/save")
    //@RequiresPermissions("product:attr:save")
    public R save(@RequestBody AttrVo attr){
        attrService.saveAttr(attr);

        return R.ok();
    }

2 service

package com.atguigu.gulimall.product.service;

import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.extension.service.IService;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.gulimall.product.entity.AttrEntity;

import java.util.Map;

/**
 * 商品属性
 *
 * @author yyl
 * @email sunlightcs@gmail.com
 * @date 2022-04-24 19:01:01
 */
public interface AttrService extends IService<AttrEntity> {

    PageUtils queryPage(Map<String, Object> params);

    void saveAttr(AttrVo attr);
}

2 serviceimpl

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        //创建一个dao实体类
        AttrEntity attrEntity = new AttrEntity();
//      attrEntity.setAttrName(attr.getAttrName());
        //把传来的基本数据传给dao实体类
        BeanUtils.copyProperties(attr,attrEntity);
        //1、保存基本数据
        this.save(attrEntity);
        //2、保存关联关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationDao.insert(relationEntity);


    }

最终测试
在这里插入图片描述
发现关系增加到了表中

29 平台属性-规格参数列表

思路 我们把规格参数的列表请求接口编写一下
能够把规格参数在前端展示出来
0
由于前端返回要求一些数据
我们创建一个返回的VO
在serviceimpl层会封装这个VO并且进行返回

package com.atguigu.gulimall.product.vo;

import lombok.Data;

@Data
public class AttrRespVo extends AttrVo {
    /**
     * 			"catelogName": "手机/数码/手机", //所属分类名字
     * 			"groupName": "主体", //所属分组名字
     */
    private String catelogName;
    private String groupName;

    private Long[] catelogPath;
}

在这里插入图片描述

1 AttrController

    @GetMapping("/{attrType}/list/{catelogId}")
    public R baseAttrList(@RequestParam Map<String, Object> params,
                          @PathVariable("catelogId") Long catelogId,
                          @PathVariable("attrType")String type){

        //1 把传入的type 参数列表 要查询哪个目录下的目录ID 用其调用service层方法
        PageUtils page = attrService.queryBaseAttrPage(params,catelogId,type);
        return R.ok().put("page", page);
    }

2 AttrService

public interface AttrService extends IService<AttrEntity> {
    PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type);

    PageUtils queryPage(Map<String, Object> params);

    void saveAttr(AttrVo attr);
}

3 AttrServiceImpl

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(type)? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        //1 创建一个新的queryWrapper AttrEntity
//        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        //2 如果传入的catelogId不为0 我们才查询catelogId
        if(catelogId != 0){
            queryWrapper.eq("catelog_id",catelogId);
        }

        //3 得到params参数列表中的Key 如果不为空 进行规则匹配(返回属性id等于Key或者是属性name like key)
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            //attr_id  attr_name
            queryWrapper.and((wrapper)->{
                wrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        //4 调用mybatis-plus serviceImpl层的page方法返回Ipage对象
        // 其参数是根据Query工具类生成的Page对象 和 queryWrapper
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        //5 把生成的Ipage对象封装到pageUtils里
        PageUtils pageUtils = new PageUtils(page);

        //6 从Ipage得到记录
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
            // 生成一个AttrRespVo的VO对象
            AttrRespVo attrRespVo = new AttrRespVo();
            // 先把原来的数据copy到其中
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            //1、设置分类和分组的名字
            if("base".equalsIgnoreCase(type)){
                AttrAttrgroupRelationEntity attrId = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (attrId != null && attrId.getAttrGroupId()!=null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrId.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }

            }


            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());

        pageUtils.setList(respVos);
        return pageUtils;
    }

后端postman发送请求观察回显
请求如下
http://localhost:88/api/product/attr/base/list/0?t=1652689194608&page=1&limit=10&key=
在这里插入图片描述
最后在前端查看显示效果

在这里插入图片描述
前端没数据可能是因为一个语法报错
(先把可选值这一列注释掉)

30 平台属性-规格修改

1 完善规格修改回显功能

我们在点击修改时发现部分数据没有回显
我们首先来添加这个回显功能

思路:回显是查询后端的@RequestMapping(“/info/{attrId}”)、
我们对其进行修改
1 AttrController

    /**
     * 信息
     */
    @RequestMapping("/info/{attrId}")
    //@RequiresPermissions("product:attr:info")
    public R info(@PathVariable("attrId") Long attrId){
        //AttrEntity attr = attrService.getById(attrId);
        //我们自定义查询详情 返回带有详细信息的respVo对象
        AttrRespVo respVo = attrService.getAttrInfo(attrId);

        return R.ok().put("attr", respVo);
    }

2 AttrService

public interface AttrService extends IService<AttrEntity> {
    PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type);

    PageUtils queryPage(Map<String, Object> params);

    void saveAttr(AttrVo attr);

    AttrRespVo getAttrInfo(Long attrId);

    void updateAttr(AttrVo attr);
}

3 impl

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        //1 新建一个respVo
        AttrRespVo respVo = new AttrRespVo();
        //2 根据传入id获取当前属性的实体类
        AttrEntity attrEntity = this.getById(attrId);
        //3 先把部分数据封装到respVO当中
        BeanUtils.copyProperties(attrEntity,respVo);

        //4 如果是基本属性
        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //1、设置分组信息
            AttrAttrgroupRelationEntity attrgroupRelation = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if(attrgroupRelation!=null){
                respVo.setAttrGroupId(attrgroupRelation.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelation.getAttrGroupId());
                if(attrGroupEntity!=null){
                    respVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }


        //2、设置分类信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        respVo.setCatelogPath(catelogPath);

        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if(categoryEntity!=null){
            respVo.setCatelogName(categoryEntity.getName());
        }


        return respVo;
    }

测试发现点击修改时已经有回显
在这里插入图片描述

2 完善规格修改功能

我们修改时发现并没有修改成功
其实是因为没有对关联表更新
这里的controller接受的是一个VO
我们来完善此功能
1 controller

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("product:attr:update")
    public R update(@RequestBody AttrVo attr){
        attrService.updateAttr(attr);

        return R.ok();
    }

2 service

public interface AttrService extends IService<AttrEntity> {
    PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type);

    PageUtils queryPage(Map<String, Object> params);

    void saveAttr(AttrVo attr);

    AttrRespVo getAttrInfo(Long attrId);

    void updateAttr(AttrVo attr);
}

3 impl

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        //1 接受前端传来的AttrVo
        AttrEntity attrEntity = new AttrEntity();
        //2 copy
        BeanUtils.copyProperties(attr,attrEntity);
        //3 先更新attrEntity
        this.updateById(attrEntity);

        //4 如果是基本属性再修改
        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //1、修改分组关联
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();

            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());

            //判断数据库中是否有这个relationEntity 有了更新 没有添加
            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if(count>0){

                relationDao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));

            }else{
                relationDao.insert(relationEntity);
            }
        }
    }

4 最终测试发现修改功能成功

31 平台属性-销售属性维护

和30的代码是一样的

32 平台属性-查询分组关联属性&删除关联

1 首先编写查询分组关联属性接口

1 AttrGroupController

    /**
     * 获取属性分组的关联的所有属性
     * @param attrgroupId
     * @return
     */
    ///product/attrgroup/{attrgroupId}/attr/relation
    @GetMapping("/{attrgroupId}/attr/relation")
    public R attrRelation(@PathVariable("attrgroupId") Long attrgroupId){
        List<AttrEntity> entities =  attrService.getRelationAttr(attrgroupId);
        return R.ok().put("data",entities);
    }

2 AttrService


/**
 * 商品属性
 *
 * @author yyl
 * @email sunlightcs@gmail.com
 * @date 2022-04-24 19:01:01
 */
public interface AttrService extends IService<AttrEntity> {
    PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type);

    PageUtils queryPage(Map<String, Object> params);

    void saveAttr(AttrVo attr);

    AttrRespVo getAttrInfo(Long attrId);

    void updateAttr(AttrVo attr);

    List<AttrEntity> getRelationAttr(Long attrgroupId);

    void deleteRelation(AttrGroupRelationVo[] vos);
}

3 AttrServiceImpl

    /**
     * 根据分组id查找关联的所有基本属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        //1 在realation表中查出所有与attrgroupId相关的realation实体类
        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        //2 拿出这些实体类对应的 属性ids
        List<Long> attrIds = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        if(attrIds == null || attrIds.size() == 0){
            return null;
        }
        //3 返回查询的数据
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }
2 编写删除关联接口

1 Controller

    /**
     * 删除属性与分组的关联关系
     * @param vos
     * @return
     */
    @PostMapping("/attr/relation/delete")
    //接受一个我们自定义的vo数组
    public R deleteRelation(@RequestBody  AttrGroupRelationVo[] vos){
        attrService.deleteRelation(vos);
        return R.ok();
    }

2 service

void deleteRelation(AttrGroupRelationVo[] vos);

3 serviceimpl

    /**
     * 删除属性与分组的关联关系
     * @param vos
     */
    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        //relationDao.delete(new QueryWrapper<>().eq("attr_id",1L).eq("attr_group_id",1L));
        //1 把vos转为relationEntity集合
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        //2 删除这些relationEntity集合
        relationDao.deleteBatchRelation(entities);
    }

32 平台属性-查询分组未关联的属性

逻辑已经加上了注释
相信你一定能看懂

1 Controller

    /**
     * 获取属性分组没有关联的其他属性
     * @param attrgroupId
     * @param params
     * @return
     */
    ///product/attrgroup/{attrgroupId}/noattr/relation
    @GetMapping("/{attrgroupId}/noattr/relation")
    public R attrNoRelation(@PathVariable("attrgroupId") Long attrgroupId,
                            @RequestParam Map<String, Object> params){
        PageUtils page = attrService.getNoRelationAttr(params,attrgroupId);
        return R.ok().put("page",page);
    }

2 Service

 PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId);

3 Serviceimpl

    /**
     * 获取当前分组没有关联的所有属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1、当前分组只能关联自己所属的分类里面的所有属性

        //1.1 根据attrgroupId获取attrGroupEntity
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        //1.2 attrGroupEntity得到catelogId
        Long catelogId = attrGroupEntity.getCatelogId();


        //2、当前分组只能关联别的分组没有引用的属性
        //2.1)、当前分类下的所有分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        // 拿到所有分组的AttrGroupId
        List<Long> collect = group.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        //2.2)、这些分组关联的属性
        List<AttrAttrgroupRelationEntity> groupId = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
        //获取attrIds
        List<Long> attrIds = groupId.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //2.3)、从当前分类的所有属性中移除这些属性;
        //当前分类下的 基本属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(attrIds!=null && attrIds.size()>0){
            wrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }

32 平台属性-新增属性和分组关联

1 controller

    /**
     * 添加属性与分组关联关系
     * @param vos
     * @return
     */
    ///product/attrgroup/attr/relation
    @PostMapping("/attr/relation")
    public R addRelation(@RequestBody List<AttrGroupRelationVo> vos){

        relationService.saveBatch(vos);
        return R.ok();
    }

2 service

void saveBatch(List<AttrGroupRelationVo> vos);

3 impl

    @Override
   public void saveBatch(List<AttrGroupRelationVo> vos) {
       //接受到vos后把其转为AttrAttrgroupRelationEntity
       //再调用批量保存方法进行保存
       List<AttrAttrgroupRelationEntity> collect = vos.stream().map(item -> {
           AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
           BeanUtils.copyProperties(item, relationEntity);
           return relationEntity;
       }).collect(Collectors.toList());
       this.saveBatch(collect);
   }

34 新增商品-调试会员等级相关接口

思路
首先确认member模块是否注册到nacos
接着编写路由规则

        - id: member_route
         uri: lb://gulimall-member
         predicates:
           - Path=/api/member/**
         filters:
           - RewritePath=/api/(?<segment>.*),/$\{segment}

导入你代码生成的vue界面
最后测试
在这里插入图片描述

35 新增商品-获取分类关联的品牌

1 controller

    /**
     *  /product/categorybrandrelation/brands/list
     *
     *  1、Controller:处理请求,接受和校验数据
     *  2、Service接受controller传来的数据,进行业务处理
     *  3、Controller接受Service处理完的数据,封装页面指定的vo
     */
    @GetMapping("/brands/list")
    public R relationBrandsList(@RequestParam(value = "catId",required = true)Long catId){
        //1 接受请求拿到传来的目录Id
        //2 调用categoryBrandRelationService的自定义方法获取BrandEntity
        List<BrandEntity> vos = categoryBrandRelationService.getBrandsByCatId(catId);

        //3 把BrandEntity进行处理封装成前端需要的BrandVo返回
        List<BrandVo> collect = vos.stream().map(item -> {
            BrandVo brandVo = new BrandVo();
            brandVo.setBrandId(item.getBrandId());
            brandVo.setBrandName(item.getName());

            return brandVo;
        }).collect(Collectors.toList());

        return R.ok().put("data",collect);

    }

2 service

List<BrandEntity> getBrandsByCatId(Long catId);

3 serviceImpl

    /**
     * 根据一个分类id查询和他有关的所有品牌实体类
     * @param catId
     * @return
     */
    @Override
    public List<BrandEntity> getBrandsByCatId(Long catId) {

        //1 首先根据分类catId查出CategoryBrandRelation表中所有关联数据
        List<CategoryBrandRelationEntity> catelogId = relationDao.selectList(new QueryWrapper<CategoryBrandRelationEntity>().eq("catelog_id", catId));
        //2 根据CategoryBrandRelationEntity 的 List 查出 brand list
        List<BrandEntity> collect = catelogId.stream().map(item -> {
            //2.1 对于每一个CategoryBrandRelationEntity 先拿出其BrandId
            Long brandId = item.getBrandId();
            //2.2 用其BrandId 调用 brandService拿到brand实体类
            BrandEntity byId = brandService.getById(brandId);
            return byId;
        }).collect(Collectors.toList());

        //3 最终返回结果
        return collect;
    }

在这里插入图片描述

报错解决 编写接口后前端扔找不到数据

首先去你的前端
在这里插入图片描述

在商品发布章节(83左右),如果遇到提示 ”PubSub “未定义错误,则需要安装 pubsub-js,具体步骤:
(1)安装 pubsub-js:
npm install --save pubsub-js
(2)在 main.js 中引入
//导入
import PubSub from ‘pubsub-js’
//挂载全局
Vue.prototype.PubSub = PubSub

36 新增商品- 获取分类下所有分组和属性

注意:前端页面编写完这个函数才会有显示
思路: 获取分类下所有分组和属性
1 AttrGroupController

    ///product/attrgroup/{catelogId}/withattr
    @GetMapping("/{catelogId}/withattr")
    public R getAttrGroupWithAttrs(@PathVariable("catelogId")Long catelogId){

        //1、查出当前分类下的所有属性分组,
        //2、查出每个属性分组的所有属性
        List<AttrGroupWithAttrsVo> vos =  attrGroupService.getAttrGroupWithAttrsByCatelogId(catelogId);
        return R.ok().put("data",vos);
    }

2 service

public interface AttrGroupService extends IService<AttrGroupEntity> {

    PageUtils queryPage(Map<String, Object> params);

    PageUtils queryPage(Map<String, Object> params, Long catelogId);

    List<AttrGroupWithAttrsVo> getAttrGroupWithAttrsByCatelogId(Long catelogId);
}

3 serviceimpl

    /**
     * 根据分类id查出所有的分组以及这些组里面的属性
     * @param catelogId
     * @return
     */
    @Override
    public List<AttrGroupWithAttrsVo> getAttrGroupWithAttrsByCatelogId(Long catelogId) {
        //com.atguigu.gulimall.product.vo
        //1、查询分组信息(列出所有与目录ID相关的分组)
        List<AttrGroupEntity> attrGroupEntities = this.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));

        //2、查询所有属性
        List<AttrGroupWithAttrsVo> collect = attrGroupEntities.stream().map(group -> {
            //创建一个返回VO
            AttrGroupWithAttrsVo attrsVo = new AttrGroupWithAttrsVo();
            //copy属性
            BeanUtils.copyProperties(group,attrsVo);
            //根据分组ID得到对应的属性函数
            List<AttrEntity> attrs = attrService.getRelationAttr(attrsVo.getAttrGroupId());
            //把得到的对应属性赋值到VO中
            attrsVo.setAttrs(attrs);
            return attrsVo;
        }).collect(Collectors.toList());

        return collect;


    }

最后发起请求测试
http://localhost:88/api/product/attrgroup/225/withattr
在这里插入图片描述
在这里插入图片描述

37 新增商品-新增商品VO抽取

先F12打开控制台
我们添加一个商品
在这里插入图片描述
然后在控制台观察其json在这里插入图片描述
我们使用json在线解析工具解析json
解析工具地址
https://www.json.cn/json/json2java.html
在这里插入图片描述
然后下载生成的代码
放到product包下的vo中

38 新增商品 商品新增业务流程分析

这一小节没有代码 看视频就行
保存spu的基本流程大体如下
在这里插入图片描述在这里插入图片描述

39 新增商品 保存SPU基本信息

stream流处理好数据之后直接调serverce用mybatis-plus进行数据保存

/**
     * //TODO 高级部分完善
     * @param vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {

        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);

        //2、保存Spu的描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());
        descEntity.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);



        //3、保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        imagesService.saveImages(infoEntity.getId(),images);


        //4、保存spu的规格参数;pms_product_attr_value

        //从vo获取规格参数list
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();

        //对vo list进行处理
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            //新建pms_product_attr_value数据库对应实体类
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            //获取每个vo项对应的id
            valueEntity.setAttrId(attr.getAttrId());
            //根据id查attr数据库中对应的实体类
            AttrEntity id = attrService.getById(attr.getAttrId());
            //查到名字封装到实体类中
            valueEntity.setAttrName(id.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(infoEntity.getId());

            return valueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);


        //5、保存spu的积分信息;gulimall_sms->sms_spu_bounds
//        Bounds bounds = vo.getBounds();
//        SpuBoundTo spuBoundTo = new SpuBoundTo();
//        BeanUtils.copyProperties(bounds,spuBoundTo);
//        spuBoundTo.setSpuId(infoEntity.getId());
//        R r = couponFeignService.saveSpuBounds(spuBoundTo);
//        if(r.getCode() != 0){
//            log.error("远程保存spu积分信息失败");
//        }


//        //5、保存当前spu对应的所有sku信息;
//
//        List<Skus> skus = vo.getSkus();
//        if(skus!=null && skus.size()>0){
//            skus.forEach(item->{
//                String defaultImg = "";
//                for (Images image : item.getImages()) {
//                    if(image.getDefaultImg() == 1){
//                        defaultImg = image.getImgUrl();
//                    }
//                }
//                //    private String skuName;
//                //    private BigDecimal price;
//                //    private String skuTitle;
//                //    private String skuSubtitle;
//                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
//                BeanUtils.copyProperties(item,skuInfoEntity);
//                skuInfoEntity.setBrandId(infoEntity.getBrandId());
//                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
//                skuInfoEntity.setSaleCount(0L);
//                skuInfoEntity.setSpuId(infoEntity.getId());
//                skuInfoEntity.setSkuDefaultImg(defaultImg);
//                //5.1)、sku的基本信息;pms_sku_info
//                skuInfoService.saveSkuInfo(skuInfoEntity);
//
//                Long skuId = skuInfoEntity.getSkuId();
//
//                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
//                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
//                    skuImagesEntity.setSkuId(skuId);
//                    skuImagesEntity.setImgUrl(img.getImgUrl());
//                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
//                    return skuImagesEntity;
//                }).filter(entity->{
//                    //返回true就是需要,false就是剔除
//                    return !StringUtils.isEmpty(entity.getImgUrl());
//                }).collect(Collectors.toList());
//                //5.2)、sku的图片信息;pms_sku_image
//                skuImagesService.saveBatch(imagesEntities);
//                //TODO 没有图片路径的无需保存
//
//                List<Attr> attr = item.getAttr();
//                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
//                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
//                    BeanUtils.copyProperties(a, attrValueEntity);
//                    attrValueEntity.setSkuId(skuId);
//
//                    return attrValueEntity;
//                }).collect(Collectors.toList());
//                //5.3)、sku的销售属性信息:pms_sku_sale_attr_value
//                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
//
//                // //5.4)、sku的优惠、满减等信息;gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
//                SkuReductionTo skuReductionTo = new SkuReductionTo();
//                BeanUtils.copyProperties(item,skuReductionTo);
//                skuReductionTo.setSkuId(skuId);
//                if(skuReductionTo.getFullCount() >0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
//                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
//                    if(r1.getCode() != 0){
//                        log.error("远程保存sku优惠信息失败");
//                    }
//                }
//
//
//
//            });
//        }

在这里插入图片描述

40 新增商品 保存SKU基本信息

/**
     * //TODO 高级部分完善
     * @param vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {

        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);

        //2、保存Spu的描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());
        descEntity.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);



        //3、保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        imagesService.saveImages(infoEntity.getId(),images);


        //4、保存spu的规格参数;pms_product_attr_value

        //从vo获取规格参数list
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();

        //对vo list进行处理
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            //新建pms_product_attr_value数据库对应实体类
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            //获取每个vo项对应的id
            valueEntity.setAttrId(attr.getAttrId());
            //根据id查attr数据库中对应的实体类
            AttrEntity id = attrService.getById(attr.getAttrId());
            //查到名字封装到实体类中
            valueEntity.setAttrName(id.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(infoEntity.getId());

            return valueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);


        //5、保存spu的积分信息;gulimall_sms->sms_spu_bounds
//        Bounds bounds = vo.getBounds();
//        SpuBoundTo spuBoundTo = new SpuBoundTo();
//        BeanUtils.copyProperties(bounds,spuBoundTo);
//        spuBoundTo.setSpuId(infoEntity.getId());
//        R r = couponFeignService.saveSpuBounds(spuBoundTo);
//        if(r.getCode() != 0){
//            log.error("远程保存spu积分信息失败");
//        }


        //5、保存当前spu对应的所有sku信息;

        //从前端传来的vo中获取sku
        List<Skus> skus = vo.getSkus();
        if(skus!=null && skus.size()>0){
            //进行skus forEach 对每一个sku进行处理
            skus.forEach(item->{
                //1 设置sku_info
                //设置默认图片
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if(image.getDefaultImg() == 1){
                        defaultImg = image.getImgUrl();
                    }
                }
                //    private String skuName;
                //    private BigDecimal price;
                //    private String skuTitle;
                //    private String skuSubtitle;
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                //5.1)、sku的基本信息;pms_sku_info
                skuInfoService.saveSkuInfo(skuInfoEntity);

                //保存到数据库后获取skuId
                Long skuId = skuInfoEntity.getSkuId();

                //2 设置skuImage
                //对每个sku对应的图片集进行处理
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity->{
                    //返回true就是需要,false就是剔除
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                //5.2)、sku的图片信息;pms_sku_image
                skuImagesService.saveBatch(imagesEntities);
                //TODO 没有图片路径的无需保存

                //3 对sku sale attr做处理
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);

                    return attrValueEntity;
                }).collect(Collectors.toList());
                //5.3)、sku的销售属性信息:pms_sku_sale_attr_value
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
//
//                // //5.4)、sku的优惠、满减等信息;gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
//                SkuReductionTo skuReductionTo = new SkuReductionTo();
//                BeanUtils.copyProperties(item,skuReductionTo);
//                skuReductionTo.setSkuId(skuId);
//                if(skuReductionTo.getFullCount() >0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
//                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
//                    if(r1.getCode() != 0){
//                        log.error("远程保存sku优惠信息失败");
//                    }
//                }
//
//
//
            });
        }


    }

在这里插入图片描述

41 新增商品 调用远程服务保存优惠等信息

1 product服务的
spuinfoseriveimpl

 /**
     * //TODO 高级部分完善
     * @param vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {

        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);

        //2、保存Spu的描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());
        descEntity.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);



        //3、保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        imagesService.saveImages(infoEntity.getId(),images);


        //4、保存spu的规格参数;pms_product_attr_value

        //从vo获取规格参数list
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();

        //对vo list进行处理
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            //新建pms_product_attr_value数据库对应实体类
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            //获取每个vo项对应的id
            valueEntity.setAttrId(attr.getAttrId());
            //根据id查attr数据库中对应的实体类
            AttrEntity id = attrService.getById(attr.getAttrId());
            //查到名字封装到实体类中
            valueEntity.setAttrName(id.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(infoEntity.getId());

            return valueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);


        //5、保存spu的积分信息;gulimall_sms->sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(infoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if(r.getCode() != 0){
            log.error("远程保存spu积分信息失败");
        }


        //5、保存当前spu对应的所有sku信息;

        //从前端传来的vo中获取sku
        List<Skus> skus = vo.getSkus();
        if(skus!=null && skus.size()>0){
            //进行skus forEach 对每一个sku进行处理
            skus.forEach(item->{
                //1 设置sku_info
                //设置默认图片
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if(image.getDefaultImg() == 1){
                        defaultImg = image.getImgUrl();
                    }
                }
                //    private String skuName;
                //    private BigDecimal price;
                //    private String skuTitle;
                //    private String skuSubtitle;
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                //5.1)、sku的基本信息;pms_sku_info
                skuInfoService.saveSkuInfo(skuInfoEntity);

                //保存到数据库后获取skuId
                Long skuId = skuInfoEntity.getSkuId();

                //2 设置skuImage
                //对每个sku对应的图片集进行处理
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity->{
                    //返回true就是需要,false就是剔除
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                //5.2)、sku的图片信息;pms_sku_image
                skuImagesService.saveBatch(imagesEntities);
                //TODO 没有图片路径的无需保存

                //3 对sku sale attr做处理
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);

                    return attrValueEntity;
                }).collect(Collectors.toList());
                //5.3)、sku的销售属性信息:pms_sku_sale_attr_value
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // //5.4)、sku的优惠、满减等信息;gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if(skuReductionTo.getFullCount() >0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if(r1.getCode() != 0){
                        log.error("远程保存sku优惠信息失败");
                    }
                }



            });
        }


    }

2
product服务的
feingn定义

package com.atguigu.gulimall.product.feign;

import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.utils.R;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

@FeignClient("gulimall-coupon")
public interface CouponFeignService {


    /**
     * 1、CouponFeignService.saveSpuBounds(spuBoundTo);
     *      1)、@RequestBody将这个对象转为json。
     *      2)、找到gulimall-coupon服务,给/coupon/spubounds/save发送请求。
     *          将上一步转的json放在请求体位置,发送请求;
     *      3)、对方服务收到请求。请求体里有json数据。
     *          (@RequestBody SpuBoundsEntity spuBounds);将请求体的json转为SpuBoundsEntity;
     * 只要json数据模型是兼容的。双方服务无需使用同一个to
     * @param spuBoundTo
     * @return
     */
    @PostMapping("/coupon/spubounds/save")
    R saveSpuBounds(@RequestBody SpuBoundTo spuBoundTo);


    @PostMapping("/coupon/skufullreduction/saveinfo")
    R saveSkuReduction(@RequestBody SkuReductionTo skuReductionTo);
}

3 coppon服务
在这里插入图片描述

    @Override
    public void saveSkuReduction(SkuReductionTo reductionTo) {
        //1、// //5.4)、sku的优惠、满减等信息;gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
        //sms_sku_ladder
        SkuLadderEntity skuLadderEntity = new SkuLadderEntity();
        skuLadderEntity.setSkuId(reductionTo.getSkuId());
        skuLadderEntity.setFullCount(reductionTo.getFullCount());
        skuLadderEntity.setDiscount(reductionTo.getDiscount());
        skuLadderEntity.setAddOther(reductionTo.getCountStatus());
        if(reductionTo.getFullCount() > 0){
            skuLadderService.save(skuLadderEntity);
        }




        //2、sms_sku_full_reduction
        SkuFullReductionEntity reductionEntity = new SkuFullReductionEntity();
        BeanUtils.copyProperties(reductionTo,reductionEntity);
        if(reductionEntity.getFullPrice().compareTo(new BigDecimal("0"))==1){
            this.save(reductionEntity);
        }


        //3、sms_member_price
        List<MemberPrice> memberPrice = reductionTo.getMemberPrice();

        List<MemberPriceEntity> collect = memberPrice.stream().map(item -> {
            MemberPriceEntity priceEntity = new MemberPriceEntity();
            priceEntity.setSkuId(reductionTo.getSkuId());
            priceEntity.setMemberLevelId(item.getId());
            priceEntity.setMemberLevelName(item.getName());
            priceEntity.setMemberPrice(item.getPrice());
            priceEntity.setAddOther(1);
            return priceEntity;
        }).filter(item->{
            return item.getMemberPrice().compareTo(new BigDecimal("0")) == 1;
        }).collect(Collectors.toList());

        memberPriceService.saveBatch(collect);
    }

42 商品保存debug

官方代码有一个小bug
导致会员价格那里的添加报空指针异常
经过debug发现
在这里插入图片描述
这一部分内容item向TO对拷失败
导致merberprice为null

接着导致空指针异常

解决方案
注释掉VO中的Merberprice
改用common模块中的Merberprice

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

43 SPU检索

对Product模块下的这个controller做操作
在这里插入图片描述

1 controller

    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("product:spuinfo:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = spuInfoService.queryPageByCondition(params);

        return R.ok().put("page", page);
    }

2 service

PageUtils queryPageByCondition(Map<String, Object> params);

3 serviceimpl

@Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        // status=1 and (id=1 or spu_name like xxx)
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }

        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId)&&!"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)&&!"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }

        /**
         * status: 2
         * key:
         * brandId: 9
         * catelogId: 225
         */

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

44 SKU检索

对skuinfoController
进行操作

1 controller

    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("product:skuinfo:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = skuInfoService.queryPageByCondition(params);

        return R.ok().put("page", page);
    }

2 service

PageUtils queryPageByCondition(Map<String, Object> params);

3 serviceimpl

@Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        /**
         * key:
         * catelogId: 0
         * brandId: 0
         * min: 0
         * max: 0
         */
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper)->{
                wrapper.eq("sku_id",key).or().like("sku_name",key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)&&!"0".equalsIgnoreCase(catelogId)){

            queryWrapper.eq("catalog_id",catelogId);
        }

        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId)&&!"0".equalsIgnoreCase(catelogId)){
            queryWrapper.eq("brand_id",brandId);
        }

        String min = (String) params.get("min");
        if(!StringUtils.isEmpty(min)){
            queryWrapper.ge("price",min);
        }

        String max = (String) params.get("max");

        if(!StringUtils.isEmpty(max)  ){
            try{
                BigDecimal bigDecimal = new BigDecimal(max);

                if(bigDecimal.compareTo(new BigDecimal("0"))==1){
                    queryWrapper.le("price",max);
                }
            }catch (Exception e){

            }

        }


        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

45 仓储服务AP+仓库管理-整合ware服务&获取仓库列表

把gulimall-ware模块
注册到nacos注册中心中
并设置开启事物 mapperscan等功能

1 application.yml配置文件

spring:
  application:
    name: gulimall-ware
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/gulimall_wms?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8
mybatis-plus:
  mapper-locations: classpath:/mapper/**/*.xml
  global-config:
    db-config:
      id-type: auto
server:
  port: 11000
logging:
  level:
    com.atguigu: debug

2 启动类

package com.atguigu.gulimall.ware;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@MapperScan("com.atguigu.gulimall.ware.dao")
@EnableTransactionManagement
@SpringBootApplication
@EnableDiscoveryClient
public class GulimallWareApplication {

    public static void main(String[] args) {
        SpringApplication.run(GulimallWareApplication.class, args);
    }

}

46 仓储服务AP个仓库管理查询库存&创建采购需求

略过

47 仓储服务API-仓库管理.合并采购需求

需要在common中创建枚举
和在ware模块中自定义Vo类
这里略过只给出代码实现
在这里插入图片描述

1 controller

    @PostMapping("/merge")
    public R merge(@RequestBody MergeVo mergeVo){

        purchaseService.mergePurchase(mergeVo);
        return R.ok();
    }

2 service

void mergePurchase(MergeVo mergeVo);

3 serviceimpl

@Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        //得到要合并的整单id
        Long purchaseId = mergeVo.getPurchaseId();

        //如果整单id为空
        if(purchaseId == null){
            //1、新建一个整单entity
            PurchaseEntity purchaseEntity = new PurchaseEntity();

            //设置整单状态
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            //设置时间
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            //保存这个实体类
            this.save(purchaseEntity);
            //保存后拿到其id
            purchaseId = purchaseEntity.getId();
        }

        //TODO 确认采购单状态是0,1才可以合并

        //得到要合并的项的id
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        //对每个项的id进行处理
        List<PurchaseDetailEntity> collect = items.stream().map(i -> {
            //新建一个PurchaseDetailEntity
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();

            //设置id
            detailEntity.setId(i);
            //设置整单的id
            detailEntity.setPurchaseId(finalPurchaseId);
            //设置状态
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());

        //集体更新PurchaseDetailEntity
        detailService.updateBatchById(collect);

        //更新整单时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

48 仓储服务=API-仓库管理:领取采购单

模拟业务员领取采购整单
http://localhost:88/api/ware/purchase/received
在这里插入图片描述

在这里插入图片描述

1 controller

    /**
     * 领取采购单
     * @return
     */
    @PostMapping("/received")
    public R received(@RequestBody List<Long> ids){

        purchaseService.received(ids);

        return R.ok();
    }

2 service

void received(List<Long> ids);

3 serviceimpl

//    /**
//     *
//     * @param ids 采购单id
//     */
    @Override
    public void received(List<Long> ids) {
        //传来的是采购整单的ids

        //1、确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            //通过ids得到每一个整单的实体类
            PurchaseEntity byId = this.getById(id);
            return byId;
        }).filter(item -> {
            //只有新建和已分配状态的采购整单才会被采购人员领取
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(item->{
            //把采购单的状态设置为已经被采购人员接收
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());

        //2、改变采购单的状态
        this.updateBatchById(collect);



        //3、改变采购项的状态
        collect.forEach((item)->{
            List<PurchaseDetailEntity> entities = detailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> detailEntities = entities.stream().map(entity -> {
                PurchaseDetailEntity entity1 = new PurchaseDetailEntity();
                entity1.setId(entity.getId());
                entity1.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return entity1;
            }).collect(Collectors.toList());
            detailService.updateBatchById(detailEntities);
        });
    }

49 仓储服务 完成采购

有很多接口的互相调用
这里只给出最主要的接口
在这里插入图片描述

1 controller

 ///ware/purchase/done
    //完成采购接口
    @PostMapping("/done")
    public R finish(@RequestBody PurchaseDoneVo doneVo){

        purchaseService.done(doneVo);

        return R.ok();
    }

2 service

void done(PurchaseDoneVo doneVo);

3 serviceimpl

@Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {

        //拿到PurchaseEntity的Id
        Long id = doneVo.getId();


        //2、改变采购项的状态
        Boolean flag = true;
        //得到vo的项
        //这里面有PurchaseDetail的id
        List<PurchaseItemDoneVo> items = doneVo.getItems();

        List<PurchaseDetailEntity> updates = new ArrayList<>();

        for (PurchaseItemDoneVo item : items) {
            //创建对应实体类
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            //如果任意一项item状态存在异常
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                //设置flag为false
                flag = false;
                //设置其状态
                detailEntity.setStatus(item.getStatus());
            }else{
                //状态没有异常 为对应实体类设置状态
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                3、将成功采购的进行入库
                PurchaseDetailEntity entity = detailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());

            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }

        detailService.updateBatchById(updates);

        //1、改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);




    }

50 商品管理-SPU规格维护

1 规格维护显示
其实是一个查询
在这里插入图片描述

在这里插入图片描述

1 controller

    // /product/attr/base/listforspu/{spuId}
    @GetMapping("/base/listforspu/{spuId}")
    public R baseAttrlistforspu(@PathVariable("spuId") Long spuId){

        List<ProductAttrValueEntity> entities = productAttrValueService.baseAttrlistforspu(spuId);

        return R.ok().put("data",entities);
    }

2 service

List<ProductAttrValueEntity> baseAttrlistforspu(Long spuId);

3 serviceimpl

    @Override
    public List<ProductAttrValueEntity> baseAttrlistforspu(Long spuId) {
        List<ProductAttrValueEntity> entities = this.baseMapper.selectList(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        return entities;
    }

2 更改规格接口编写

在这里插入图片描述

1 controller

    @PostMapping("/update/{spuId}")
    public R updateSpuAttr(@PathVariable("spuId") Long spuId,
                           @RequestBody List<ProductAttrValueEntity> entities){

        productAttrValueService.updateSpuAttr(spuId,entities);

        return R.ok();
    }

2 service

void updateSpuAttr(Long spuId, List<ProductAttrValueEntity> entities);

3 serviceimpl

    @Transactional
    @Override
    public void updateSpuAttr(Long spuId, List<ProductAttrValueEntity> entities) {
        //1、删除这个spuId之前对应的所有属性
        this.baseMapper.delete(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id",spuId));


        List<ProductAttrValueEntity> collect = entities.stream().map(item -> {
            item.setSpuId(spuId);
            return item;
        }).collect(Collectors.toList());
        this.saveBatch(collect);
    }

51 基础篇总结与感想

在这里插入图片描述

总之是断断续续的完成了基础篇

中间有过几次迷茫 经历过许多问题 版本冲突 数据库问题 配置问题等等
有一段时间失去继续下去的动力
但都最后解决并坚持下来

也许这次学习不会给未来找工作带来太大优势

但当你坚持下来 你对商城业务的流程会有些许了解

克服重重报错和bug 坚持向前的经历值得记忆

如果你看到这里

共勉

接下来会继续学习高级篇

欢迎继续观看笔记

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐