1. 导包
- <dependencies>
- // 将 domain quary 写到了这层
- <dependency>
- <groupId>cn.xxx.aigou</groupId>
- <artifactId>qqq_product_interface</artifactId>
- <version>1.0-SNAPSHOT</version>
- </dependency>
- <!--springboot 相关的依赖 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- </dependency>
- <!--mp 的依赖 -->
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-boot-starter</artifactId>
- <version>2.2.0</version>
- </dependency>
- <dependency>
- <groupId>MySQL</groupId>
- <artifactId>MySQL-connector-java</artifactId>
- <version>5.1.20</version>
- </dependency>
- <!--eureka 的客户端 -->
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
- </dependency>
- <!--swagger2 接口文档依赖 -->
- <dependency>
- <groupId>io.springfox</groupId>
- <artifactId>springfox-swagger2</artifactId>
- <version>2.9.2</version>
- </dependency>
- <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
- <dependency>
- <groupId>io.springfox</groupId>
- <artifactId>springfox-swagger-ui</artifactId>
- <version>2.9.2</version>
- </dependency>
- <!-- 配置中心支持 -->
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-config</artifactId>
- </dependency>
- </dependencies>
2.contrlloer 实现
- /**
- * 树状结构数据查询:
- * @return
- */
- @RequestMapping(value = "/treeData",method = RequestMethod.GET)
- public List<ProductType> treeData()
- {
- return productTypeService.treeData();
- }
3.service 写逻辑
- @Override
- public List<ProductType> treeData() {
- /*
- 使用循环的方式获取不同层次的节点
- */
- return treeDataLoop();
- }
- private List<ProductType> treeDataLoop() {
- //1: 首先查询出所有的数据
- List<ProductType> allProductTypes = productTypeMapper.selectList(null);
- // 获取所有的数据的 key--value 的值
- Map<Long,ProductType> map=new HashMap<>();
- for (ProductType pt : allProductTypes) {
- map.put(pt.getId(),pt);
- }
- // 最终返回的结果: 一级菜单
- List<ProductType> result=new ArrayList<>();
- //2: 遍历: 封装父节点和子节点
- for (ProductType currentProductType : allProductTypes) {
- // 判断是否是一级菜单
- if(currentProductType.getPid()==0){
- // 如果是一级菜单则返回
- result.add(currentProductType);
- }else{
- ProductType parent =map.get(currentProductType.getPid());
- parent.getChildren().add(currentProductType);
- }
- }
- return result;
- }
3. 前台写好后, 直接测试
来源: http://www.bubuko.com/infodetail-3007022.html