当前位置: 首页 > news >正文

Hutool TreeUtil快速构建树形数据结构

在管理菜单、部门结构等场景时,我们经常需要将数据库中的层级数据转换为树形结构。本文将通过Hutool的TreeUtil工具类,实现零递归快速构建树形结构。

一、环境准备

  • JDK 1.8+
  • Spring Boot 2.x
  • Hutool 5.8.16
  • MySQL 8.0

二、数据准备

-- 创建部门表
CREATE TABLE `sys_dept` (`id` int NOT NULL AUTO_INCREMENT,`dept_name` varchar(50) NOT NULL COMMENT '部门名称',`parent_id` int NOT NULL DEFAULT '0' COMMENT '父部门ID',`sort` int DEFAULT '0' COMMENT '排序',PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;-- 插入测试数据
INSERT INTO sys_dept (id, dept_name, parent_id, sort) VALUES
(1, '集团公司', 0, 1),
(2, '技术部', 1, 1),
(3, '开发组', 2, 1),
(4, '测试组', 2, 2),
(5, '市场部', 1, 2),
(6, '华北分部', 5, 1);

三、代码实现

1. 添加Hutool依赖

<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.16</version></dependency>

2. 实体类

/*** * @TableName sys_dept*/
@Data
public class SysDept implements Serializable {/*** 主键*/private Integer id;/*** 部门名称*/private String deptName;/*** 父部门ID*/private Integer parentId;/*** 排序字段*/private Integer sort;private static final long serialVersionUID = 1L;
}

3. Mapper接口

@Mapper
public interface SysDeptMapper {List<SysDept> listAll();
}

4. Service实现


@Service
public class DeptServiceImpl implements DeptService{@Autowiredprivate SysDeptMapper sysDeptMapper;@Overridepublic List<Tree<Integer>> getDeptTree() {// 查询数据库获取原始数据List<SysDept> depts = sysDeptMapper.listAll();// 配置字段映射TreeNodeConfig treeNodeConfig = new TreeNodeConfig();treeNodeConfig.setIdKey("id");treeNodeConfig.setParentIdKey("parentId");treeNodeConfig.setWeightKey("sort"); // 排序字段treeNodeConfig.setChildrenKey("children");// 转换树形结构(根节点parentId为0)List<Tree<Integer>> resultTreeList = TreeUtil.build(depts, 0, treeNodeConfig,(treeNode, tree) -> {tree.setId(treeNode.getId());tree.setParentId(treeNode.getParentId());tree.putExtra("deptName", treeNode.getDeptName());tree.putExtra("sort", treeNode.getSort());});return resultTreeList;}
}

5. Controller

@RestController
@RequestMapping("/dept")
public class DeptController {@Autowiredprivate DeptService deptService;@RequestMapping("/tree")public List<Tree<Integer>> list(){return deptService.getDeptTree();}
}

四、结果示例

请求GET /dept/tree返回:

[{"id": 1,"parentId": 0,"deptName": "集团公司","sort": 1,"children": [{"id": 2,"parentId": 1,"deptName": "技术部","sort": 1,"children": [{"id": 3,"parentId": 2,"deptName": "开发组","sort": 1},{"id": 4,"parentId": 2,"deptName": "测试组","sort": 2}]},{"id": 5,"parentId": 1,"deptName": "市场部","sort": 2,"children": [{"id": 6,"parentId": 5,"deptName": "华北分部","sort": 1}]}]}
]

五、技术要点

1. TreeNodeConfig配置

  • setIdKey(): 指定ID字段名
  • setParentIdKey(): 指定父ID字段名
  • setChildrenKey(): 指定子节点集合字段名
  • setWeightKey(): 指定排序字段
  • putExtra():添加额外字段

参考:
https://doc.hutool.cn/pages/TreeUtil/

相关文章:

  • 简易版2D我的世界C++程序(有点BUG,但是可以玩!!!)
  • 教育领域的AIGC革命:构建多模态智能教学系统
  • Java 安全:如何保护敏感数据?
  • pytorch python常用指令
  • GoLang基础
  • Java ThreadLocal与内存泄漏
  • SD模型的评估指标(挖坑中..)
  • 【强化学习(实践篇)】#1 多臂赌博机网格世界
  • 腾讯云智三道算法题
  • chrony服务器(1)
  • Python赋能教育:构建智能考试评分系统的最佳实践
  • 上位机知识篇---时钟分频
  • Android学习总结之自定义View绘制源码理解
  • springboot入门-controller层
  • 多系统安装经验,移动硬盘,ubuntu grub修改/etc/fstab 移动硬盘需要改成nfts格式才能放steam游戏
  • YOLOv8改进新路径:Damo-YOLO与Dyhead融合的创新检测策略
  • 第三方测试机构如何保障软件质量并节省企业成本?
  • Xilinx FPGA支持的FLASH型号汇总
  • git 工具
  • 架构进阶:105页PPT学习数字化转型企业架构设计手册【附全文阅读】
  • 以军称若停火谈判无进展,将大幅扩大加沙军事行动
  • 我驻阿巴斯总领馆:将持续跟踪港口爆炸事件进展,全力确保中方人员安全
  • “梅花奖”快闪走入上海张园,朱洁静在石库门前起舞
  • 游戏论|迟来的忍者与武士:从《刺客信条:影》论多元话语的争议
  • 强政神鸟——故宫里的乌鸦
  • 甘肃省原副省长赵金云被开除公职,甘肃省委表态:坚决拥护党中央决定