1.关系图
2.数据库表t_company及对应实体类Company.class
package com.zhl.model;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
@Data
@Table(name="t_company")
public class Company {
@Id
@GeneratedValue(generator="JDBC")
private Long id;
private String name;
private Long parentId;
}
3.树状图封装实体类TreeBo.class
package com.zhl.common.bo;
import java.util.List;
import lombok.Data;
@Data
public class TreeBo {
private Long id;
private String name;
private Long pid;
private List<TreeBo> children;
public TreeBo() {
super();
}
public TreeBo(Long id, String name, Long pid, List<TreeBo> children) {
super();
this.id = id;
this.name = name;
this.pid = pid;
this.children = children;
}
public TreeBo(Long id, String name, Long pid) {
super();
this.id = id;
this.name = name;
this.pid = pid;
}
}
4.树状图工具类(核心)TreeUtil.class
package com.zhl.utils;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zhl.common.bo.TreeBo;
public class TreeUtil {
private List<TreeBo> rootList; // 根节点对象存放到这里
private List<TreeBo> bodyList; // 其他节点存放到这里,可以包含根节点
public TreeUtil(List<TreeBo> rootList, List<TreeBo> bodyList) {
this.rootList = rootList;
this.bodyList = bodyList;
}
public List<TreeBo> getTree() { // 调用的方法入口
if (bodyList != null && !bodyList.isEmpty()) {
// 声明一个map,用来过滤已操作过的数据
Map<Long, Long> map = Maps.newHashMapWithExpectedSize(bodyList.size());
rootList.forEach(beanTree -> getChild(beanTree, map));
return rootList;
}
return null;
}
private void getChild(TreeBo beanTree, Map<Long, Long> map) {
List<TreeBo> childList = Lists.newArrayList();
bodyList.stream().filter(c -> !map.containsKey(c.getId())).filter(c -> c.getPid().equals(beanTree.getId()))
.forEach(c -> {
map.put(c.getId(), c.getPid());
getChild(c, map);
childList.add(c);
});
beanTree.setChildren(childList);
}
}
5.业务层将表数据封装并调用树状图工具类
public List<TreeBo> listTree() {
/** 获取所有表数据*/
List<Company> companyList = companyMapper.selectAll();
List<TreeBo> rootList = new ArrayList<>();
List<TreeBo> bodyList = new ArrayList<>();
for (Company company : companyList) {
if (company.getParentId()==null) {
/** 根结点列表*/
rootList.add(new TreeBo(company.getId(), company.getName(), company.getParentId()));
}else {
/** 其他结点列表(可以包含根结点)*/
bodyList.add(new TreeBo(company.getId(), company.getName(), company.getParentId()));
}
}
TreeUtil treeUtil = new TreeUtil(rootList, bodyList);
return treeUtil.getTree();
}
6.返回数据结果
[{
"id": 1,
"name": "总集团",
"pid": null,
"children": [{
"id": 2,
"name": "子集团1",
"pid": 1,
"children": [{
"id": 4,
"name": "公司1",
"pid": 2,
"children": []
}, {
"id": 6,
"name": "公司3",
"pid": 2,
"children": []
}, {
"id": 7,
"name": "公司4",
"pid": 2,
"children": []
}, {
"id": 9,
"name": "公司2",
"pid": 2,
"children": []
}]
}, {
"id": 3,
"name": "子集团2",
"pid": 1,
"children": [{
"id": 5,
"name": "公司2",
"pid": 3,
"children": []
}, {
"id": 8,
"name": "公司5",
"pid": 3,
"children": []
}]
}]
}]