spingcloud微服务_04_商品模块

前言:

做一个微服务的商品模块。会用到的技术:springboot、springcloud、mybatisPlus、mybatisPlus的代码生成器(根据template模板生成)…

一、项目准备

(1)准备数据库表

会用到的三张表:商品分类=>商品品牌=>商品
spingcloud微服务_04_商品模块_第1张图片

(2)三张数据库表分析

spingcloud微服务_04_商品模块_第2张图片

(3)在公共基础子模块aigou_basic_parent中的aigou_basic_util工具模块中拷贝工具类进去

spingcloud微服务_04_商品模块_第3张图片

(4)创建商品项目结构

先创建项目的商品子模块父工程aigou_product_parent,然后再在aigou_product_parent中创建一个公共接口模块aigou_product_interface和服务模块aigou_product_service

spingcloud微服务_04_商品模块_第4张图片

(5)模块与模块之间引入依赖,进行关联

在商品的服务service模块的pom.xml中引入接口interface模块的依赖,然后接口interface模块的pom.xml中又要引用公共基础模块中的aigou_basic_util工具模块的依赖

spingcloud微服务_04_商品模块_第5张图片

(6)使用mybatisPlus代码生成

在这篇mybatisPlus入门学习 的博客中已经用过代码生成。所以这次就直接在原项目mp_parent中使用代码生成。在资源文件resources中改动代码生成后的路径、数据库的一些配置,以及修改config包中的配置文件中的表名、生成的目录路径等等配置。

1)、要生成controller层和query层代码,就需要template模板

在原项目mp_parent的资源文件中准备controller和query的template模板,用来生成两层的代码
spingcloud微服务_04_商品模块_第6张图片

  • controller的模板。(CRUD操作的模板)
package ${package.Controller};

import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import cn.lyq.aigou.util.AjaxResult;
import cn.lyq.aigou.util.PageList;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/${table.entityPath}")
public class ${entity}Controller {
    @Autowired
    public ${table.serviceName} ${table.entityPath}Service;

    /**
    * 保存和修改公用的
    * @param ${table.entityPath}  传递的实体
    * @return Ajaxresult转换结果
    */
    @RequestMapping(value="/add",method= RequestMethod.POST)
    public AjaxResult save(@RequestBody ${entity} ${table.entityPath}){
        try {
            if(${table.entityPath}.getId()!=null){
                ${table.entityPath}Service.updateById(${table.entityPath});
            }else{
                ${table.entityPath}Service.insert(${table.entityPath});
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("保存对象失败!"+e.getMessage());
        }
    }

    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @RequestMapping(value="/delete/{id}",method=RequestMethod.DELETE)
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            ${table.entityPath}Service.deleteById(id);
            return AjaxResult.me();
        } catch (Exception e) {
        e.printStackTrace();
            return AjaxResult.me().setMsg("删除对象失败!"+e.getMessage());
        }
    }

    //获取用户
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public ${entity} get(@RequestParam(value="id",required=true) Long id)
    {
        return ${table.entityPath}Service.selectById(id);
    }

    /**
    * 查看所有的员工信息
    * @return
    */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public List<${entity}> list(){

        return ${table.entityPath}Service.selectList(null);
    }

    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @RequestMapping(value = "/json",method = RequestMethod.POST)
    public PageList<${entity}> json(@RequestBody ${entity}Query query)
    {
        Page<${entity}> page = new Page<${entity}>(query.getPage(),query.getRows());
            page = ${table.entityPath}Service.selectPage(page);
            return new PageList<${entity}>(page.getTotal(),page.getRecords());
    }
}

  • query的模板
package cn.lyq.aigou.product.query;
import cn.lyq.aigou.util.BaseQuery;

/**
 *
 * @author ${author}
 * @since ${date}
 */
public class ${table.entityName}Query extends BaseQuery{
}

2)、在商品子模块aigou_product_service服务模块的pom.xml中引入依赖


    
    
        cn.lyq
        aigou_product_interface
        1.0-SNAPSHOT
    
    
    
        org.springframework.boot
        spring-boot-starter-web
    
    
        org.springframework.boot
        spring-boot-starter-test
    
    
    
        mysql
        mysql-connector-java
    

    
    
        org.springframework.cloud
        spring-cloud-starter-config
    

    
    
        org.springframework.cloud
        spring-cloud-starter-netflix-eureka-client
    

    
    
    
        io.springfox
        springfox-swagger2
        2.9.2
    
    
    
        io.springfox
        springfox-swagger-ui
        2.9.2
    

3)、在商品子模块aigou_product_interface接口模块的pom.xml中引入依赖

mybatisPlus的依赖


   
   
       cn.lyq
       aigou_basic_util
       1.0-SNAPSHOT
   
   
   
       com.baomidou
       mybatis-plus-boot-starter
       2.2.0
   

4)、原项目mp_parent中修改的resources资源文件中的代码生成配置文件mpconofig.properties为

#此处为本项目src所在路径(代码生成器输出路径),注意一定是当前项目所在的目录哟
OutputDir=H:\\IDEA\\idea_workspace\\aigou_parent\\aigou_product_parent\\aigou_product_service\\src\\main\\java

#mapper.xml SQL映射文件目录
OutputDirXml=H:\\IDEA\\idea_workspace\\aigou_parent\\aigou_product_parent\\aigou_product_service\\src\\main\\resources

#我们生产代码要放的项目的地址:
OutputDirBase=H:\\IDEA\\idea_workspace\\aigou_parent\\aigou_product_parent\\aigou_product_service\\src\\main\\java

#我们生产代码要放的项目的地址:(可用作query层的生成目录)
OutputDirInterface=H:\\IDEA\\idea_workspace\\aigou_parent\\aigou_product_parent\\aigou_product_interface\\src\\main\\java
#设置作者
author=lyqtest
#自定义包路径,自动生成的包名
parent=cn.lyq.aigou.product

#数据库连接信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///aigou
jdbc.user=root
jdbc.pwd=123456

5)、在config包中修改的代码生成配置类GenteratorCode.java

以后可以直接拷贝过去修改即可使用

package cn.lyq.aigou.mp;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.*;

public class GenteratorCode {

    public static void main(String[] args) throws InterruptedException {
        //用来获取Mybatis-Plus.properties文件的配置信息
        final ResourceBundle rb = ResourceBundle.getBundle("mpconfig");
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(rb.getString("OutputDir"));
        //覆盖
        gc.setFileOverride(true);
        gc.setActiveRecord(true);// 开启 activeRecord 模式
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
        gc.setAuthor(rb.getString("author"));
        //生成代码运行后不弹出生成的文件路径盘符
        gc.setOpen(false);
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        //设置你数据库类型:
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert());
        dsc.setDriverName(rb.getString("jdbc.driver"));
        dsc.setUsername(rb.getString("jdbc.user"));
        dsc.setPassword(rb.getString("jdbc.pwd"));
        dsc.setUrl(rb.getString("jdbc.url"));
        mpg.setDataSource(dsc);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setTablePrefix(new String[] { "t_" });// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategy.setInclude(new String[]{"t_brand"}); // 需要生成的表
        mpg.setStrategy(strategy);
        // 包配置
        PackageConfig pc = new PackageConfig();
        // parent:cn.itsource.aigou.mp
        pc.setParent(rb.getString("parent"));
        pc.setController("controller");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setEntity("domain");
        pc.setMapper("mapper");
        mpg.setPackageInfo(pc);

        // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map map = new HashMap();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb");
                this.setMap(map);
            }
        };

        List focList = new ArrayList();

        // 调整 domain 生成目录演示
        focList.add(new FileOutConfig("/templates/entity.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirInterface")+ "/cn/lyq/aigou/product/domain/" + tableInfo.getEntityName() + ".java";
            }
        });

        // 调整 xml 生成目录演示:本来mybatis的mapper.xml应该放到resources下:路径应该和Mapper.java的路径一致:
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirXml")+ "/cn/lyq/aigou/product/mapper/" + tableInfo.getEntityName() + "Mapper.xml";
            }
        });

        // 调整 controller 生成目录演示
        focList.add(new FileOutConfig("/templates/controller.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirBase")+ "/cn/lyq/aigou/product/controller/" + tableInfo.getEntityName() + "Controller.java";
            }
        });


        // 调整 query 生成目录演示
        focList.add(new FileOutConfig("/templates/query.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirInterface")+ "/cn/lyq/aigou/product/query/" + tableInfo.getEntityName() + "Query.java";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
        // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
        TemplateConfig tc = new TemplateConfig();
        tc.setService("/templates/service.java.vm");
        tc.setServiceImpl("/templates/serviceImpl.java.vm");
        tc.setEntity(null);
        tc.setMapper("/templates/mapper.java.vm");
        tc.setController(null);
        tc.setXml(null);
        // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
        mpg.setTemplate(tc);
        // 执行生成
        mpg.execute();
    }
}

6)、最后在aigou_parent项目中生成的代码结构图示

  • 接口interface子模块
    spingcloud微服务_04_商品模块_第7张图片
  • service服务子模块
    spingcloud微服务_04_商品模块_第8张图片

(7)网关&swagger&注册中心客户端等的配置

对上面根据商品品牌表t_brand生成的service服务子模块的代码进行zuul网关、swagger接口和eureka注册中心客户端等配置。

1)、先在aigou_product_service模块中创建个启动类

@SpringBootApplication
@EnableEurekaClient// eureka的客户端
@MapperScan(basePackages="cn.lyq.aigou.product.mapper") //mapper和xml都扫描了
public class ProductApplication8002 {
    public static void main(String[] args) {
        SpringApplication.run(ProductApplication8002.class);
    }
}

2)、在aigou_product_service模块中创建个config配置包,放入swagger的配置类

@Configuration
@EnableSwagger2
public class Swagger2 {
 
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.lyq.aigou.product.controller"))
                //包:就是自己接口的包路径
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("商品系统api")//名字
                .description("商品系统接口文档说明")//额外藐视
                .contact(new Contact("wbtest", "", "[email protected]"))
                .version("1.0")// 版本
                .build();
    }
}

3)、在aigou_product_service模块中进行YMAL配置application.yml文件(没有放入配置中心的时候)

server:
  port: 8002
spring:
  application:
    name: AIGOU-PRODUCT
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql:///aigou
    username: root
    password: 123456
eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka
mybatis-plus:
  type-aliases-package: cn.lyq.aigou.product.domain,cn.lyq.aigou.product.query #配置mapper映射中的别名

4)、在网关模块aigou_zuul_server_9527的YAML配置中进行商品服务的配置

spingcloud微服务_04_商品模块_第9张图片

5)、使用swagger接口管理

之前第2)步已经创建了swagger的配置类,并在pom.xml中引入了swagger的依赖

6)、测试

启动注册中心7001、再启动商品服务8002、启动网关9527、

  • 都启动好之后,在浏览器地址栏输入地址:http://localhost:9527/swagger-ui.html 查看一下
    spingcloud微服务_04_商品模块_第10张图片

二、CRUD操作

在上面的操作中,已经将controller类中的接口交给了swagger管理,所以接下来进行增删改查操作

1、根据id查询一条数据

spingcloud微服务_04_商品模块_第11张图片

2、增加一条数据

spingcloud微服务_04_商品模块_第12张图片

3、更新一条数据

由于在controller层的template模板中,添加方法add中已经做了id判断,有id就是修改操作,没有id就是增加操作。

spingcloud微服务_04_商品模块_第13张图片

4、删除操作

spingcloud微服务_04_商品模块_第14张图片

三、分页查询功能

1、分页功能实现

(1)、在aigou_product_service模块的config包中创建mybatisPlus的分页插件类

//Spring boot方式
@EnableTransactionManagement
@Configuration
@MapperScan("cn.lyq.aigou.product.mapper")
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

(2)、工具类模块aigou_basic_util中在上面拷贝插件类的时候已经将分页需要的数据类PageList拷好了。

//分页对象:easyui只需两个属性,total(总数),datas(分页数据)就能实现分页
public class PageList {
    private long total;
    private List rows = new ArrayList<>();

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public List getRows() {
        return rows;
    }

    public void setRows(List rows) {
        this.rows = rows;
    }

    @Override
    public String toString() {
        return "PageList{" +
                "total=" + total +
                ", rows=" + rows +
                '}';
    }

    //提供有参构造方法,方便测试
    public PageList(long total, List rows) {
        this.total = total;
        this.rows = rows;
    }
    //除了有参构造方法,还需要提供一个无参构造方法
    public PageList() {
    }
}

(3)、query的父类BaseQuery中有查询的关键字KeyWord以及分页的当前页和每页条数的参数

public class BaseQuery {
    //query做为查询: keyword
    private String keyword;//查询关键字

    private Integer page=1;//当前页 currentPage
    private Integer rows=10;//每页条数  pageSize

    public String getKeyword() {
        return keyword;
    }

    public void setKeyword(String keyword) {
        this.keyword = keyword;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getRows() {
        return rows;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }
}

(4)、通过代码生成器生成的aigou_product_service模块的BrandController类中的分页方法

/**
 * 分页查询数据:
 * 前台输入查询条件:
 *     封装到query对象:
 *        关键字条件:
 *        分页对象的条件:
 * @param query 查询对象
 * @return PageList 分页对象
 */
@RequestMapping(value = "/json",method = RequestMethod.POST)
public PageList json(@RequestBody BrandQuery query){
    //page对象是baomidou包中的
    Page page = new Page(query.getPage(),query.getRows());
    //mybatisPlus的selectPage方法需要一个page对象参数
        page = brandService.selectPage(page);
        //返回给前台分页数据对象PageList。而参数page.getTotal()总条数和page.getRecords()数据方法都是baomidou包中的
        return new PageList(page.getTotal(),page.getRecords());
}

(5)、在swagger中测试

spingcloud微服务_04_商品模块_第15张图片

(6)、遇到的问题:在上面的分页查询中关键字KeyWord没起作用,接下来完善。

2、完善分页查询中关键字KeyWord

(1)、使用代码生成器生成商品分类productType的代码

(2)、分析商品品牌Brand类和商品分类ProductType类

两者表关系是一(商品分类)对多(商品品牌)关系,多表查询就要配置。此处就要在商品品牌Brand实体类中增加一个商品分类ProductType的对象字段

/**
 * 

* 品牌信息 *

* @author lyqtest * @since 2019-05-10 * 通过mybatisPlus的注解@TableName给xml映射文件表明查这个表,通过 @TableField表名实体类和表中的字段不一致 */ @TableName("t_brand")//mybatisPlus的注解,类上面打上表名的注解 public class Brand extends Model { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; private Long createTime; private Long updateTime; /** * 商品分类ID */ @TableField("product_type_id")//标识表中的字段是这样的,解决字段不一致 private Long productTypeId; //商品品牌brand和商品分类productType是多对一关系。 @TableField(exist = false)//告诉数据库表t_brand中不存在这个字段。数据库操作就忽略它 private ProductType productType; /** * 用户姓名 */ private String name; /** * 英文名 */ private String englishName; /** * 首字母 */ private String firstLetter; private String description; private Integer sortIndex; /** * 品牌LOGO */ private String logo; public ProductType getProductType() { return productType; } public void setProductType(ProductType productType) { this.productType = productType; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getCreateTime() { return createTime; } public void setCreateTime(Long createTime) { this.createTime = createTime; } public Long getUpdateTime() { return updateTime; } public void setUpdateTime(Long updateTime) { this.updateTime = updateTime; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEnglishName() { return englishName; } public void setEnglishName(String englishName) { this.englishName = englishName; } public String getFirstLetter() { return firstLetter; } public void setFirstLetter(String firstLetter) { this.firstLetter = firstLetter; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getProductTypeId() { return productTypeId; } public void setProductTypeId(Long productTypeId) { this.productTypeId = productTypeId; } public Integer getSortIndex() { return sortIndex; } public void setSortIndex(Integer sortIndex) { this.sortIndex = sortIndex; } public String getLogo() { return logo; } public void setLogo(String logo) { this.logo = logo; } @Override protected Serializable pkVal() { return this.id; } @Override public String toString() { return "Brand{" + "id=" + id + ", createTime=" + createTime + ", updateTime=" + updateTime + ", productTypeId=" + productTypeId + ", productType=" + productType + ", name='" + name + '\'' + ", englishName='" + englishName + '\'' + ", firstLetter='" + firstLetter + '\'' + ", description='" + description + '\'' + ", sortIndex=" + sortIndex + ", logo='" + logo + '\'' + '}'; } }
  • 重要部分代码图示:
    spingcloud微服务_04_商品模块_第16张图片

(3)、分析PageList对象

该对象是返回给前台接收的对象。此对象需要两个参数total和rows,因此需要两条sql,一条查询条数,一条查询数据

spingcloud微服务_04_商品模块_第17张图片

(4)、在BrandMapper.xml映射文件中写相应的SQL语句。

注意:Brand中还有productType的关联属性,所以要进行手动映射。是对象就用,集合则用。此处是商品分类对象





    
    
        
        
        
        
        
        
        
        
        
        
    

    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
            
            
        
    

    
    

    
    

    
    
        
            
                b.name like  CONCAT('%',#{keyword},'%') or b.englishName like CONCAT('%',#{keyword},'%')
            
        
    

  • 重要部分图示:
    spingcloud微服务_04_商品模块_第18张图片

(5)、BaseQuery中的针对xml映射文件中分页的开始索引配置

spingcloud微服务_04_商品模块_第19张图片

(6)、在BrandMapper.java中写对应xml映射文件中的sql语句方法

spingcloud微服务_04_商品模块_第20张图片

(7)、在service层写相应的接口和实现

  • service接口:IBrandService

spingcloud微服务_04_商品模块_第21张图片

  • service的实现类:BrandServiceImpl
    调用了mapper层中的两个方法来满足service层的这一个方法
    spingcloud微服务_04_商品模块_第22张图片

(8)、controller层

spingcloud微服务_04_商品模块_第23张图片

(9)、测试完成高级查询+分页

spingcloud微服务_04_商品模块_第24张图片

四、商品品牌前台页面展示

1、展示数据




  • 基于之前修改的代码图示

spingcloud微服务_04_商品模块_第25张图片

  • 最后前台页面展示
    spingcloud微服务_04_商品模块_第26张图片

2、商品品牌页面的CRUD操作

(1)、整体的商品品牌brand.vue的js代码





(2)、高级查询+分页功能

spingcloud微服务_04_商品模块_第27张图片

(3)、增加数据

spingcloud微服务_04_商品模块_第28张图片

(4)、删除数据

spingcloud微服务_04_商品模块_第29张图片

(5)、修改数据

spingcloud微服务_04_商品模块_第30张图片

五、商品类型的树状结构展示

1、商品类型的数据库表展示

字段pid表示层级关系
spingcloud微服务_04_商品模块_第31张图片

2、elementUi的树状结构图

spingcloud微服务_04_商品模块_第32张图片

3、最终商品类型树状图要展示的效果

spingcloud微服务_04_商品模块_第33张图片

4、在商品类型类中增加一个children字段

spingcloud微服务_04_商品模块_第34张图片

5、controller层

在这里插入图片描述

6、实现树状结构的第一种方法:递归方式

spingcloud微服务_04_商品模块_第35张图片

(1)、service层准备接口方法

在这里插入图片描述

(2)、service层的实现类

树状结构重要的代码

@Service
public class ProductTypeServiceImpl extends ServiceImpl implements IProductTypeService {

    //注入mapper对象
    @Autowired
    private ProductTypeMapper productTypeMapper;

    //实现树状结构
    @Override
    public List treeData() {
        //递归方法。查看商品类型数据库表得知pid=0为最上一级,返回前台的都是一级菜单
        return treeDataRecursion(0L);
    }

    /**
     * 递归:
     *   自己方法里调用自己,但是必须有一个出口:没有儿子就出去;
     *  好么:
     *   不好,因为每次都要发送sql,就要发送很多的sql:
     *     要耗时;数据库的服务器要承受很多的访问量,压力大。
     *   ====》原因是发送了很多sql,我优化就少发送,至少发送1条。
     * @return
     */
    public List treeDataRecursion(Long pid){
        //拿到所有的一级菜单。调用下面的getAllChildren方法
        List allChildren = getAllChildren(pid);
        //设置一个出口:没有儿子就不用遍历,直接返回null
        if(allChildren==null||allChildren.size()==0){
            return null;
        }
        //否则,就要遍历找到当前对象的所有儿子
        for (ProductType child : allChildren) {
            //调用自己的方法,找到自己的儿子。
                //看数据库表就能明白。根据自己的对象的id找自己的儿子
            List productTypes = treeDataRecursion(child.getId());
            //再将自己的儿子存放进来。productType实体类中的set方法
            child.setChildren(productTypes);
        }
        //返回装好的菜单
        return allChildren;
    }

    /**
     * 查询数据的pid=pid的:
     *  // select * from t_product_type where pid = 2
     * @param pid
     * @return
     */
    public List getAllChildren(Long pid){
        //准备baomidou包的wrapper对象
        Wrapper wrapper=new EntityWrapper<>();
        //wrapper的eq方法:参数是数据库列名和数据值。查询数据库中列名为pid,并且传进来的参数为pid的数据
        wrapper.eq("pid", pid);
        //mybatisPlus的selectList方法需要一个wrapper对象
        return productTypeMapper.selectList(wrapper);
    }
}
  • 画图解释一波上面的代码构成
    spingcloud微服务_04_商品模块_第36张图片

7、再使用循环的方式实现商品分类的树状图

递归方式每次都要发送sql,数据库要接收很多的访问量,压力大。循环方式:发送一条sql语句,然后在内存中组装父子关系

spingcloud微服务_04_商品模块_第37张图片

(1)、service层接口方法

在这里插入图片描述

(2)、service层实现类

@Service
public class ProductTypeServiceImpl extends ServiceImpl implements IProductTypeService {

    //注入mapper对象
    @Autowired
    private ProductTypeMapper productTypeMapper;

    //实现树状结构
    @Override
    public List treeData() {
        //循环方法。返回前台的都是一级菜单
        return treeDataLoop();
    }

    /**
     * 步骤:循环查询
     * 1:先查询出所有的数据
     * 2:再组装父子结构
     * @return
     */
    public List treeDataLoop() {
        //返回的一级菜单
        List result = new ArrayList<>();
        //1.先查询出所有的数据。selectList方法的参数mapper为null即可
        List productTypes = productTypeMapper.selectList(null);

        //定义一个map集合。参数是id和productType类
        Map map=new HashMap<>();
        //再循环查出来的对象,放到map集合中去
        for (ProductType cur : productTypes) {
            //将对象的id和对象放map集合中去
            map.put(cur.getId(), cur);
        }
        //2.组装父子结构。遍历上面查询到的数据,拿到当前对象
        for (ProductType current : productTypes) {
            //找到一级菜单
            if(current.getPid()==0){
                //装到上面定义的result集合中去
                result.add(current);
            }else{
                //否则就不是一级菜单,你是儿子。那么是哪个对象的儿子?
                //先定义一个老子菜单
                ProductType parent=null;

                /*嵌套循环了,更加影响数据库性能,所以不用,用上面定义的map集合方式存放查询出来的数据
                /再循环查出来的数据
                for (ProductType cur : productTypes) {
                    //如果cur对象的id就是current对象的pid,那么cur对象就是老子。多找一下表中的id和pid的关系
                    if(cur.getId()==current.getPid()){
                        //cur对象就是老子
                        parent=cur;
                    }
                }
                */
                //和上面嵌套循环一个意思。如果map集合中的cur对象的id就是current对象的pid,那么cur对象就是老子。多找一下表中的id和pid的关系
                parent = map.get(current.getPid());
                //然后拿到老子的儿子
                List children = parent.getChildren();
                //然后将你自己加进去。你自己是你老子的儿子
                children.add(current);
            }
        }
        //返回装好的一级菜单
        return result;
    }
}
  • 画图解释一波
    spingcloud微服务_04_商品模块_第38张图片

你可能感兴趣的:(springcloud微服务)