JAVA如何把数据库的数据处理成树形结构

 更新时间:2021年09月24日 09:06:34   作者:菜菜bu菜  
本文介绍了JAVA如何把数据库的数据处理成树形结构,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

前言

不知道大家在做项目的时候有没有接触到将平平无奇数据结合处理成有层次的数据呢,类似下面这样

在这里插入图片描述

或者 生活处处都有,我想大家都应该接触过的,下面直接看怎么实现,我会大概讲一下思路,当然也可以直接跳到最后去看代码实现的哈

follow me!go go go!

❗此篇文章也只是一个简单的学习记录,不详细的对代码进行讲解

😎实现思路😎

首先一般数据库的模型设计如下

在这里插入图片描述

sql脚本

-- ----------------------------
-- Table structure for product
-- ----------------------------
DROP TABLE IF EXISTS `product`;
CREATE TABLE `product` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `uuid` varchar(64) NOT NULL,
  `name` varchar(100) NOT NULL COMMENT '名称',
  `sort` int(11) DEFAULT NULL COMMENT '排序',
  `parent_uuid` varchar(64) NOT NULL DEFAULT '-1' COMMENT '父亲 无父级为-1',
  `level` varchar(10) NOT NULL COMMENT '产品层级',
  `create_time` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COMMENT='产品表';

-- ----------------------------
-- Records of product
-- ----------------------------
INSERT INTO `product` VALUES ('1', '4dbf40d2-2af7-425c-a103-0349caaa26cf', '生产类', '1', '-1', '1', '2021-09-23 15:34:36');
INSERT INTO `product` VALUES ('2', '3062deff-8ec7-44c4-bd4e-88fe3c7b835c', '22', '1', '4dbf40d2-2af7-425c-a103-0349caaa26cf', '2', '2021-09-23 15:37:20');
INSERT INTO `product` VALUES ('3', '32afe426-9337-41c1-83e8-caf3248ba57e', '互联网信息', '2', '4dbf40d2-2af7-425c-a103-0349caaa26cf', '2', '2021-09-23 15:38:19');
INSERT INTO `product` VALUES ('4', '34c5239f-db2d-4394-b367-a57f8ae6f8ff', '33', '1', '3062deff-8ec7-44c4-bd4e-88fe3c7b835c', '3', '2021-09-23 15:53:29');
INSERT INTO `product` VALUES ('5', '19eedcd3-aa7f-4a2d-8182-d3f795e99b9d', '44', '1', '34c5239f-db2d-4394-b367-a57f8ae6f8ff', '4', '2021-09-23 15:53:56');

我们观察一下,可以发现我们的关注重点在name、uuid、parent_uuid上面:

  • name:分类名称
  • uuid:UUID 是 通用唯一识别码(Universally Unique Identifier)的缩写,是一种软件建构的标准,其目的,是让分布式系统中的所有元素,都能有唯一的辨识信息,而不需要通过中央控制端来做辨识信息的指定。这里可以简单看作一个唯一标识码(类似于ID但不等于ID)
  • parent_uuid:子类的父类UUID,最高级规定为-1(这个可以自己定义,不会有相同的就好)

下面就是我创建的模拟数据

在这里插入图片描述

想要实现数形状结构,肯定要以某一属性来作为突破口,它就是parent_uuid,那么到底是如何实现的 来看具体代码

完整代码

只贴重点代码

首先使用了Mabatis-generator生成了通用后端代码,结构如下:

在这里插入图片描述

ProductController.class

package com.csdn.caicai.test.modules.product.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import com.csdn.caicai.test.modules.product.dto.ProductRsp;
import com.csdn.caicai.test.modules.product.biz.IProductBiz;

import java.util.List;


/**
 * 产品表
 *
 * @author
 * @date
 */

@RestController
@Api(tags = {"产品表"})
@RequestMapping("/caicai/product")
@Validated
public class ProductController {
    private static final Logger log = LoggerFactory.getLogger(ProductController.class);

    @Autowired
    private IProductBiz productBiz;

    /**
     * 产品树
     */
    @ApiOperation(value = "产品树")
    @RequestMapping(path = "/tree", method = RequestMethod.GET)
    public List<ProductRsp> tree() {
        return  productBiz.tree();
    }
}

IProductBiz.class

package com.csdn.caicai.test.modules.product.biz;


import com.csdn.caicai.test.modules.product.dto.ProductRsp;

import java.util.List;

/**
 * @author
 * @date
 */
public interface IProductBiz {


    List<ProductRsp> tree();
}

ProductBiz.class

package com.csdn.caicai.test.modules.product.biz;


import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

import tk.mybatis.mapper.entity.Example;

import com.csdn.caicai.test.modules.product.service.IProductService;
import com.csdn.caicai.test.modules.product.dao.entity.ProductEntity;
import com.csdn.caicai.test.modules.product.dto.ProductReq;
import com.csdn.caicai.test.modules.product.dto.ProductRsp;

import static java.util.stream.Collectors.toList;

/**
 * @author
 * @date
 */
@Service("productBiz")
public class ProductBiz implements IProductBiz {
    @Autowired
    private  IProductService productService;
    /**
     * 根据条件查询
     *
     * @param productReq
     * @return
     */
    public List<ProductEntity> selectByCondition(ProductReq productReq) {
        Example example = new Example(ProductEntity.class);
        //下面添加自定义收索条件


        return productService.selectByExample(example);
    }

    @Override
    public List<ProductRsp> tree() {
        ProductReq req = new ProductReq();
        List<ProductRsp> list = selectByCondition(req).stream().map(this::productConvert).collect(Collectors.toList());
        return buildTree(list, req.getParentUuid());
    }

    private ProductRsp productConvert(ProductEntity e) {
        ProductRsp orgNode = new ProductRsp();
        orgNode.setId(e.getId());
        orgNode.setUuid(e.getUuid());
        orgNode.setName(e.getName());
        orgNode.setLevel(e.getLevel());
        orgNode.setSort(e.getSort());
        orgNode.setParentUuid(e.getParentUuid());
        return orgNode;
    }

    public static List<ProductRsp> buildTree(List<ProductRsp> all, String parentUuid) {
        if (CollectionUtils.isEmpty(all))
            return Lists.newArrayList();

        List<ProductRsp> parentList = all.stream()
                .filter(e -> StringUtils.isBlank(e.getParentUuid())
                        || "-1".equals(e.getParentUuid())
                        || e.getParentUuid().equals(parentUuid))
                .collect(toList());

        getSubList(parentList, all);

        return parentList;
    }

    private static void getSubList(List<ProductRsp> parentList, List<ProductRsp> all) {
        parentList.forEach(e -> {
            List<ProductRsp> subList = all.stream().filter(o -> o.getParentUuid().equals(e.getUuid())).collect(toList());
            e.setSubList(subList);
            if (!CollectionUtils.isEmpty(subList))
                getSubList(subList, all);
        });
    }
}

ProductReq.class

package com.csdn.caicai.test.modules.product.dto;



import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;

/**
* @author
* @date
*/
@ApiModel(value = "ProductReq", description = "产品表")
@Data
public class ProductReq implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
     *
     */
    @ApiModelProperty(value = "", name = "id")
    private Long id;
	/**
     *
     */
    @ApiModelProperty(value = "", name = "uuid")
    private String uuid;
	/**
     * 名称
     */
    @ApiModelProperty(value = "名称", name = "name")
    private String name;
	/**
     * 排序
     */
    @ApiModelProperty(value = "排序", name = "sort")
    private Integer sort;
	/**
     * 父亲 无父级为-1
     */
    @ApiModelProperty(value = "父亲 无父级为-1", name = "parentUuid")
    private String parentUuid;
	/**
     * 产品层级
     */
    @ApiModelProperty(value = "产品层级", name = "level")
    private String level;
}


ProductRsp.class

package com.csdn.caicai.test.modules.product.dto;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;

import java.util.Date;
import java.util.List;

/**
* @author
* @date
*/
@ApiModel(value = "ProductRsp", description = "产品表")
@Data
public class ProductRsp implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
     *
     */
    @ApiModelProperty(value = "", name = "id")
    private Long id;
	/**
     *
     */
    @ApiModelProperty(value = "", name = "uuid")
    private String uuid;
	/**
     * 名称
     */
    @ApiModelProperty(value = "名称", name = "name")
    private String name;
	/**
     * 排序
     */
    @ApiModelProperty(value = "排序", name = "sort")
    private Integer sort;
	/**
     * 父亲 无父级为-1
     */
    @ApiModelProperty(value = "父亲 无父级为-1", name = "parentUuid")
    private String parentUuid;
	/**
     * 产品层级
     */
    @ApiModelProperty(value = "产品层级", name = "level")
    private String level;
	/**
     *
     */
    @ApiModelProperty(value = "", name = "createTime")
    private Date createTime;

    @ApiModelProperty(value = "下属产品", name = "subList")
    private List<ProductRsp> subList;
}

测试一下

在这里插入图片描述

可以看到,实现了我们的效果

总结-核心代码

上面罗里吧嗦,其实核心代码就是以下代码,亲们来试着理解一下,然后就可以在此基础上美化一下就好了:
ProductRsp、ProductReq 是实体类,可以自行替换里面的内容

  private ProductRsp productConvert(ProductEntity e) {
        ProductRsp orgNode = new ProductRsp();
        orgNode.setId(e.getId());
        orgNode.setUuid(e.getUuid());
        orgNode.setName(e.getName());
        orgNode.setLevel(e.getLevel());
        orgNode.setSort(e.getSort());
        orgNode.setParentUuid(e.getParentUuid());
        return orgNode;
    }

    public static List<ProductRsp> buildTree(List<ProductRsp> all, String parentUuid) {
        if (CollectionUtils.isEmpty(all))
            return Lists.newArrayList();

        List<ProductRsp> parentList = all.stream()
                .filter(e -> StringUtils.isBlank(e.getParentUuid())
                        || "-1".equals(e.getParentUuid())
                        || e.getParentUuid().equals(parentUuid))
                .collect(toList());

        getSubList(parentList, all);

        return parentList;
    }

    private static void getSubList(List<ProductRsp> parentList, List<ProductRsp> all) {
        parentList.forEach(e -> {
            List<ProductRsp> subList = all.stream().filter(o -> o.getParentUuid().equals(e.getUuid())).collect(toList());
            e.setSubList(subList);
            if (!CollectionUtils.isEmpty(subList))
                getSubList(subList, all);
        });
    }

到此这篇关于JAVA如何把数据库的数据处理成树形结构的文章就介绍到这了,更多相关JAVA如何把数据库的数据处理成树形结构内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Hibernate Validator实现更简洁的参数校验及一个util

    Hibernate Validator实现更简洁的参数校验及一个util

    这篇文章主要介绍了Hibernate Validator实现更简洁的参数校验及一个util,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-05-05
  • SpringBoot整合Mybatis与thymleft实现增删改查功能详解

    SpringBoot整合Mybatis与thymleft实现增删改查功能详解

    MybatisPlus是国产的第三方插件, 它封装了许多常用的CURDapi,免去了我们写mapper.xml的重复劳动。本文将整合MybatisPlus实现增删改查功能,感兴趣的可以了解一下
    2022-12-12
  • mybatis的if判断不要使用boolean值的说明

    mybatis的if判断不要使用boolean值的说明

    这篇文章主要介绍了mybatis的if判断不要使用boolean值的说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-11-11
  • 深入解析@InitBinder注解的功能与应用

    深入解析@InitBinder注解的功能与应用

    这篇文章主要介绍了深入解析@InitBinder注解的功能与应用,从字面意思可以看出这个的作用是给Binder做初始化的,被此注解的方法可以对WebDataBinder初始化,webDataBinder是用于表单到方法的数据绑定的,需要的朋友可以参考下
    2023-10-10
  • Java集成swagger文档组件

    Java集成swagger文档组件

    这篇文章主要介绍了Java集成swagger文档组件,通过详细的图文介绍和代码分析展示,从头展开说明详细的过程,希望对你的开发有所帮助
    2021-06-06
  • Lombok的@Accessors使用说明

    Lombok的@Accessors使用说明

    这篇文章主要介绍了Lombok的@Accessors使用说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2025-03-03
  • 详解spring如何使用注解开发

    详解spring如何使用注解开发

    今天给大家整理了spring如何使用注解开发这篇文章,文中有非常详细的介绍及代码示例,对正在学习的小伙伴们很有帮助,需要的朋友可以参考下
    2021-05-05
  • Eclipse的Debug调试技巧大全(总结)

    Eclipse的Debug调试技巧大全(总结)

    这篇文章主要介绍了Eclipse的Debug调试技巧大全(总结),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • sin(x)如何求解的java代码实现方法

    sin(x)如何求解的java代码实现方法

    这篇文章主要为大家介绍了sin(x)如何求解的java代码实现方法示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-04-04
  • idea中导入项目后main方法无法Run的解决

    idea中导入项目后main方法无法Run的解决

    这篇文章主要介绍了idea中导入项目后main方法无法Run的解决方案,具有很好的参考价值,希望对大家有所帮助。
    2023-03-03

最新评论