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/