后台构建树形结构

该博客介绍了如何优化后台接口,减少数据库调用次数,通过一次性查询所有数据,然后使用集合循环构建前端所需的树形结构数据。方法包括查询根节点和递归获取子节点,最终实现前端Vue页面的树形组件展示。这种方法提高了效率,避免了多次数据库交互。
摘要由CSDN通过智能技术生成

后台:
前端需要的数据格式如下,即需要在后台构建这种格式的数据:

treeData:[
{
	label:"",
	children:
	[
		{label:"",children:[{...}]}
	]
}
]

1.查询根节点:

public List<Map> taxTreeList(String taxcode){
    List<Map> mapList = new ArrayList<Map>();
    //查询根节点
    List<TaxCode> list = productMapper.taxTreeListByCode(taxcode);
    for(TaxCode taxcode1:list){
        mapList.add(this.selctSonList(taxcode1));
    }
    return mapList;
}

2.根据父节点查询子节点

public Map selctSonList(TaxCode taxcode){
    Map map = new HashMap();
    map.put("label",taxcode.getTaxcode());
    //根据父节点查询子节点
    List<TaxCode> list =  productMapper.taxTreeListByCode(taxcode.getTaxcode());
    if(list.size()>0){
        List<Map> list1 = new ArrayList<Map>();
        for(TaxCode tax:list){
       		//根据父节点查询子节点
            list1.add(this.selctSonList(tax));
        }
        map.put("children",list1);
    };
    return map;
}

前端:
vue页面:

<el-tree ref="tree" :data="treeData" :props="props">
  <span class="span-ellipsis" slot-scope="{node,data}">
    <span :title="data.label" style="font-size: 14px;">{{data.label}}</span>
  </span>
</el-tree>

·treeData为后台返回的数据;
·label为树形结构展示的内容

效果如下图:
效果图

------------------------------------分割线--------------------------------
以上方法是需要多次调用数据库的,更新一个一次性查询数据然后用集合去循环的,逻辑跟上面差不多~

public List<Map> taxTreeList(){
	//访问数据库
	List<Map> l = testMapper.getList();
	List<Map> list = new ArrayList<>();
	for(int i=0;i<l.size();i++){
	   //获取每一个根节点的id
	   if(Long.parseLong(l.get(i).get("pid").toString())==0){
	       list.add(this.getList(l,l.get(i)));
	   }
	}
	return list;
}
//m表示父节点对象
public Map getList(List<Map> l,Map m){
   Map map = new HashMap();
    map.put("label",m.get("name"));
    //根据父节点id获取子节点
    List<Map> list = new ArrayList<>();
    for(int i=0;i<l.size();i++){
        if(m.get("id").toString().equals(l.get(i).get("pid").toString())){
            list.add(this.getList(l,l.get(i)));
        }
        map.put("children",list);
    }
    return map;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值