項目中用到的服務器返回給前端樹列表代碼實現
使用sql將根節點下所有子節點都查詢出來返回給Java端,只根據parentId查詢,沒有Level等級的需求
select node_id,parent_id,ischild from
(
select
t1.node_id,
parent_id,
if(find_in_set(parent_id, @pids) > 0, @pids := concat(@pids,',',node_id), 'not found') as ischild
from (select t.node_id,t.parent_id from t_rbac_node t order by parent_id, node_id) t1,
(select @pids := 10 id) t2
)t3
where ischild != 'not found'
union all
#連上根節點自己
select node_id,parent_id,null from t_rbac_node where node_id=10
java代碼使用遞歸的方法將數據庫返回的數據組裝成tree
@Override
public NodeTreeVO getNodeTree(Integer parentId,int[] level) throws Exception {
Map<String,Object> paramMap=new HashMap<String,Object>();
paramMap.put("parentId",parentId);
paramMap.put("level",level);
List<NodeTreeVO> nodeRoleRespVOS = nodeDOMapper.selectNodeTree(paramMap);
return getNodeTree(nodeRoleRespVOS,parentId);
}
/**
* @Description 組裝結果
* @author xpWang
* @date 2020/1/15 16:52
*/
private NodeTreeVO getNodeTree(List<NodeTreeVO> dblist,Integer parentId){
List<NodeTreeVO> result=new ArrayList<NodeTreeVO>();
NodeTreeVO root=null;
//獲取根節點
int index=0;
for(;index<dblist.size();index++){
if (parentId==dblist.get(index).getNodeId()){
root=dblist.get(index);
break;
}
}
if (root==null){
return null;
}
dblist.remove(index);
result.add(root);
getNodeTree(result,dblist);
return root;
}
/**
* @Description 將dblist裏面的數據插入到resultlist下,遞歸調用
* @author xpWang
* @date 2020/1/15 16:53
*/
public List<NodeTreeVO> getNodeTree(List<NodeTreeVO> result,List<NodeTreeVO> dblist){
for(NodeTreeVO node:result){
for (int i=0;i<dblist.size();i++){
NodeTreeVO nodeTreeVO=dblist.get(i);
if (dblist.get(i).getParentId()==node.getNodeId()){
node.addNode(dblist.get(i));
dblist.remove(i);
i--;
}
}
getNodeTree(node.getChildren(),dblist);
}
return result;
}
返回給前端的DTO
@Data
public class NodeTreeVO extends NodeDO {
private List<NodeTreeVO> children=new ArrayList<NodeTreeVO>();
public void addNode(NodeTreeVO node){
children.add(node);
}
}