目标:把一个关系型数据库中<子,父>关系的并列型列表转换成为一个层级架构树。
DB:
parent node------ -------
soft_1 staff_B
soft_1 staff_C
dev soft_1
dev soft_2
dev staff_A
gm_A dev
gm_A hr
gm_A market
hr staff_E
soft_2 staff_D
boss gm_A
NULL boss
最终架构树:
boss | gm_A | dev | soft_1 | staff_B |
staff_C | ||||
soft_2 | staff_D | |||
staff_A | ||||
market | ||||
hr | staff_E |
这种情况需要用到递归。
主程序:
FileOrganizationNode treeNode = new FileOrganizationNode();
List<FileOrganization> fileOrganizations = new ArrayList<FileOrganization>();
fileOrganizations = fileOrganizationService.findNodeByOrganizationName(organizationName, limit);
treeNode.setName(rootNode.getNodeName());
addTreeNode(treeNode, rootNode.getNodeName(), fileOrganizations); // 递归插入子node
* fileOrganizations 就是上面的<子,父>列表,rootNode.getNodeName() 取值为"boss"。
FileOrganization(包含其它内容) / FileOrganizationNode(只有子、父名)
/**
*
* file_organization
*
* 组织上下级关系描述
*
*/
public class FileOrganization {
private String nodeName;
private String nodeParentName;
...
public class FileOrganizationNode {
private String name;
private List<FileOrganizationNode> children;
addTreeNode方法:
// 递归插入子node
public void addTreeNode(FileOrganizationNode treeNode, String parentNode, List<FileOrganization> fileOrganizations) {
final Integer DEF_VALUE = 20;
List<FileOrganizationNode> childTreeNodes = new ArrayList<FileOrganizationNode>();
for (FileOrganization fileOrganization:fileOrganizations) {
if (parentNode.equals(fileOrganization.getNodeParentName())) {
FileOrganizationNode childTreeNode = new FileOrganizationNode();
childTreeNode.setName(fileOrganization.getNodeName());
childTreeNode.setValue(DEF_VALUE);
childTreeNode.setNodeType(fileOrganization.getNodeType());
childTreeNodes.add(childTreeNode);
// 通过传参childTreeNode串联递归
addTreeNode(childTreeNode, fileOrganization.getNodeName(), fileOrganizations);
}
}
if (!childTreeNodes.isEmpty()) {
treeNode.setChildren(childTreeNodes);
}
}
treeNode内容:
参考:
递归例子(Javascript)http://blog.csdn.net/textboy/article/details/46544379