1 依赖包
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.11</version>
</dependency>
2 案列
假设我们有一个层级的表 parentid就是他的上一级
2.1 代码
public List<Tree<Integer>> getAll() {
List<Dept> deptList = deptMapper.selectAll();
TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
treeNodeConfig.setIdKey("id");
treeNodeConfig.setParentIdKey("parentId");
// 设置层级 也就是有几级子目录这种关系
treeNodeConfig.setDeep(3);
List<Tree<Integer>> build = TreeUtil.build(deptList, 0, treeNodeConfig, (treeNode, tree) -> {
tree.setId(treeNode.getId()); //id
tree.setParentId(treeNode.getParentId()); //父id
//TODO 返回的时候字段
tree.putExtra("id",treeNode.getId());
tree.putExtra("parentId",treeNode.getParentId());
tree.putExtra("name",treeNode.getName());
});
return build;
}
}
解释:
首先就是获取全部的数据
TreeNodeConfig 进行一些配置
然后就是转换器 putExtra
TreeNodeConfig默认的配置是:
private String idKey = "id"; 主键id
private String parentIdKey = "parentId"; 父id
private String weightKey = "weight"; 根据权重进行排序
private String nameKey = "name";
private String childrenKey = "children";