1.數據庫表設計
2.實體類設計
1 package com.ieou.capsule.dto.SystemPermissions; 2 3 import java.util.List; 4 5 /** 6 * 功能菜單類 7 */ 8 public class SystemPermissionsTree { 9 10 private String functionCode;//菜單碼 11 12 private String parentFunctionCode;//父級菜單碼 13 14 private String functionName;//菜單名 15 16 private Boolean flag; // true:選中 false:未選中 17 18 private List<SystemPermissionsTree> childrenList; 19 20 public String getFunctionCode() { 21 return functionCode; 22 } 23 24 public void setFunctionCode(String functionCode) { 25 this.functionCode = functionCode; 26 } 27 28 public String getParentFunctionCode() { 29 return parentFunctionCode; 30 } 31 32 public void setParentFunctionCode(String parentFunctionCode) { 33 this.parentFunctionCode = parentFunctionCode; 34 } 35 36 public String getFunctionName() { 37 return functionName; 38 } 39 40 public void setFunctionName(String functionName) { 41 this.functionName = functionName; 42 } 43 44 public Boolean getFlag() { 45 return flag; 46 } 47 48 public void setFlag(Boolean flag) { 49 this.flag = flag; 50 } 51 52 public List<SystemPermissionsTree> getChildrenList() { 53 return childrenList; 54 } 55 56 public void setChildrenList(List<SystemPermissionsTree> childrenList) { 57 this.childrenList = childrenList; 58 } 59 }
3.遞歸工具類
1 package com.ieou.capsule.util; 2 3 import com.ieou.capsule.dto.SystemPermissions.SystemPermissionsTree; 4 5 import java.util.ArrayList; 6 import java.util.List; 7 8 public class TreeUtil { 9 /** 10 * 作者:一沐楓一 11 * 來源:CSDN 12 * 原文:https://blog.csdn.net/gxgl8811/article/details/72803833 13 * 版權聲明:本文為博主原創文章,轉載請附上博文鏈接! 14 */ 15 16 public static List<SystemPermissionsTree> getTreeList(List<SystemPermissionsTree> entityList) { 17 List<SystemPermissionsTree> resultList = new ArrayList<>(); 18 19 //獲取頂層元素集合 20 String parentCode; 21 for (SystemPermissionsTree entity : entityList) { 22 parentCode = entity.getParentFunctionCode(); 23 //頂層元素的parentCode==null或者為0 24 if (parentCode == null || "0".equals(parentCode)) { 25 resultList.add(entity); 26 } 27 } 28 29 //獲取每個頂層元素的子數據集合 30 for (SystemPermissionsTree entity : resultList) { 31 entity.setChildrenList(getSubList(entity.getFunctionCode(), entityList)); 32 } 33 34 return resultList; 35 } 36 37 /** 38 * 獲取子數據集合 39 * 40 * @param id 41 * @param entityList 42 * @return 43 * @author jianda 44 * @date 2017年5月29日 45 */ 46 private static List<SystemPermissionsTree> getSubList(String id, List<SystemPermissionsTree> entityList) { 47 List<SystemPermissionsTree> childList = new ArrayList<>(); 48 String parentId; 49 50 //子集的直接子對象 51 for (SystemPermissionsTree entity : entityList) { 52 parentId = entity.getParentFunctionCode(); 53 if (id.equals(parentId)) { 54 childList.add(entity); 55 } 56 } 57 58 //子集的間接子對象 59 for (SystemPermissionsTree entity : childList) { 60 entity.setChildrenList(getSubList(entity.getFunctionCode(), entityList)); 61 } 62 63 //遞歸退出條件 64 if (childList.size() == 0) { 65 return null; 66 } 67 68 return childList; 69 } 70 71 72 }