一、準備表結構及對應的表數據
a、表結構:java
create table TB_TREE ( CID NUMBER not null, CNAME VARCHAR2(50), PID NUMBER //父節點 )
b、表數據:node
insert into tb_tree (CID, CNAME, PID) values (1, '中國', 0); insert into tb_tree (CID, CNAME, PID) values (2, '北京市', 1); insert into tb_tree (CID, CNAME, PID) values (3, '廣東省', 1); insert into tb_tree (CID, CNAME, PID) values (4, '上海市', 1); insert into tb_tree (CID, CNAME, PID) values (5, '廣州市', 3); insert into tb_tree (CID, CNAME, PID) values (6, '深圳市', 3); insert into tb_tree (CID, CNAME, PID) values (7, '海珠區', 5); insert into tb_tree (CID, CNAME, PID) values (8, '天河區', 5); insert into tb_tree (CID, CNAME, PID) values (9, '福田區', 6); insert into tb_tree (CID, CNAME, PID) values (10, '南山區', 6); insert into tb_tree (CID, CNAME, PID) values (11, '密雲縣', 2); insert into tb_tree (CID, CNAME, PID) values (12, '浦東', 4);
二、TreeNode對象,對應tb_tree算法
public class TreeNode implements Serializable { private Integer cid; private String cname; private Integer pid; private List nodes = new ArrayList(); public TreeNode() { } //getter、setter省略 }
三、測試數據json
public class TreeNodeTest { @Test public void loadTree() throws Exception{ System.out.println(JsonUtils.javaToJson(recursiveTree(1))); } /** * 遞歸算法解析成樹形結構 * * @param cid * @return * @author jiqinlin */ public TreeNode recursiveTree(int cid) { //根據cid獲取節點對象(SELECT * FROM tb_tree t WHERE t.cid=?) TreeNode node = personService.getreeNode(cid); //查詢cid下的全部子節點(SELECT * FROM tb_tree t WHERE t.pid=?) List childTreeNodes = personService.queryTreeNode(cid); //遍歷子節點 for(TreeNode child : childTreeNodes){ TreeNode n = recursiveTree(child.getCid()); //遞歸 node.getNodes().add(n); } return node; } }
輸出的json格式以下:測試
{ "cid": 1, "nodes": [ { "cid": 2, "nodes": [ { "cid": 11, "nodes": [ ], "cname": "密雲縣", "pid": 2 } ], "cname": "北京市", "pid": 1 }, { "cid": 3, "nodes": [ { "cid": 5, "nodes": [ { "cid": 7, "nodes": [ ], "cname": "海珠區", "pid": 5 }, { "cid": 8, "nodes": [ ], "cname": "天河區", "pid": 5 } ], "cname": "廣州市", "pid": 3 }, { "cid": 6, "nodes": [ { "cid": 9, "nodes": [ ], "cname": "福田區", "pid": 6 }, { "cid": 10, "nodes": [ ], "cname": "南山區", "pid": 6 } ], "cname": "深圳市", "pid": 3 } ], "cname": "廣東省", "pid": 1 }, { "cid": 4, "nodes": [ { "cid": 12, "nodes": [ ], "cname": "浦東", "pid": 4 } ], "cname": "上海市", "pid": 1 } ], "cname": "中國", "pid": 0 }