您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
利用递归算法怎么将数据库解析成Java树形结构?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
1、准备表结构及对应的表数据
a、表结构:
create table TB_TREE ( CID NUMBER not null, CNAME VARCHAR2(50), PID NUMBER //父节点 )
b、表数据:
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);
2、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省略 }
3、测试数据
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 }
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。