項目開發中,幾乎沒法避免的會遇到樹形結構,今天和你們分享java後端如何處理數據爲樹形結構。javascript
前端處理樹形結構,後端生成樹形結構。前端
Entity實體層:java
此處省略好幾個實體字段。 /** * 孩子節點集合 */ private List<OrganizationVO> child = new ArrayList<OrganizationVO>();
Controller層:算法
OrganizationVO list = organizationService.selectCategoryAndChildrenById(id);
Service業務層:後端
/** * 遞歸查詢本節點的id和孩子節點的id * @param id * @return */ OrganizationVO selectCategoryAndChildrenById(Long id);
ServiceImpl業務實現:ide
/** * 遞歸查詢本節點的id和孩子節點的id * * @param id * @return */ @Override public OrganizationVO selectCategoryAndChildrenById(Long id) { return findChildCatgoryBak(id); } /** * 遞歸算法-算出子節點 */ public OrganizationVO findChildCatgoryBak(Long orgId) { List<OrganizationVO> childList = new ArrayList<>(); // 經過id獲取全部VO信息 OrganizationVO organizationVO = iOrganizationService.get(orgId); //查找子節點,遞歸程序必需要有一個出口 List<OrganizationVO> organizationList = iOrganizationService.getChildren(null, orgId); //organizationVO.setChild(organizationList); for (OrganizationVO item : organizationList) { childList.add(findChildCatgoryBak(item.getId())); } organizationVO.setChild(childList); return organizationVO; }
業務之中的判斷本身能夠加上,好比經過Id獲取這條信息是否爲null。測試
測試結果:code
{ "code": 0, "message": "獲取組織成功", "items": { "id": 2, "createTime": null, "modifyTime": "2020-04-21 16:37:35", "creatorId": 0, "modifierId": 0, "parentId": 0, "orgName": "電子商品", "orgState": "ENABLE", "description": "", "orgSort": 1, "child": [ { "id": 3, "createTime": "2020-04-21 16:41:07", "modifyTime": "2020-04-22 10:40:52", "creatorId": 0, "modifierId": 0, "parentId": 2, "orgName": "電腦", "orgState": "ENABLE", "description": "", "orgSort": 1, "child": [ { "id": 21, "createTime": "2020-04-23 23:11:45", "modifyTime": "2020-04-23 23:11:45", "creatorId": null, "modifierId": null, "parentId": 3, "orgName": "筆記本電腦", "orgState": "ENABLE", "description": "是佛山東莞給", "orgSort": null, "child": [] } ] }, { "id": 13, "createTime": "2020-04-22 16:34:08", "modifyTime": "2020-04-22 16:34:08", "creatorId": null, "modifierId": null, "parentId": 2, "orgName": "新增組織1", "orgState": "ENABLE", "description": "", "orgSort": 4, "child": [] }, { "id": 14, "createTime": "2020-04-22 19:07:58", "modifyTime": "2020-04-22 19:07:58", "creatorId": null, "modifierId": null, "parentId": 2, "orgName": "測試", "orgState": "ENABLE", "description": "是佛山東莞給", "orgSort": null, "child": [] }, { "id": 16, "createTime": "2020-04-23 10:13:26", "modifyTime": "2020-04-23 10:13:26", "creatorId": null, "modifierId": null, "parentId": 2, "orgName": "112", "orgState": "ENABLE", "description": null, "orgSort": null, "child": [] }, { "id": 20, "createTime": "2020-04-23 22:33:10", "modifyTime": "2020-04-23 22:33:10", "creatorId": null, "modifierId": null, "parentId": 2, "orgName": "測試1111111", "orgState": "ENABLE", "description": null, "orgSort": 3, "child": [] } ] } }