后端数据构建前台树

公司最近有个业务,一次性查询表数据后组装成树,数据结构类似如下
在这里插入图片描述
需要组装成树形结构
bean:

public class TreeNode{
	private int id;
	private String name;
	private String value;
	private int pId;
	public TreeNode(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public String getValue() {
		return value;
	}

	public TreeNode setValue(String value) {
		this.value = value;
		return this;
	}

	public int getPId() {
		return pId;
	}

	public TreeNode setPId(int pId) {
		this.pId = pId;
		return this;
	}
}

util:

public class PackTreeNodeUtil {
	public static TreeNode pack(List<TreeNode> tree,
								TreeNode prevNode, TreeNode nextNode,
								Map<String,Integer>checkMap){
    	String checkValue = prevNode.getId()+prevNode.getId()+nextNode.getValue();//增加主节点和前一个节点值进行判断
    	//如果不存在则新建节点
    	if(!checkMap.containsKey(checkValue)){
    		checkMap.put(checkValue, tree.size());
    		tree.add(nextNode.setPId(prevNode.getId()));
		}else{
			//找出原来的节点
			nextNode = tree.get(checkMap.get(checkValue));
		}
    	return nextNode;
    }
}

web:

@RestController
    public class AdressController {
        @Resource
        private AdressService adressService;
        @GetMapping("tree")
        public Object tree(){
            List<Adress> all = adressService.findAll();
            List<TreeNode> tree = new ArrayList<>();
            int id = 0;
            Map<String,Integer> checkMap = new HashMap<>();
            TreeNode root = new TreeNode(0,"主节点").setValue("主节点");
            tree.add(root);
            for (Adress adress : all) {
                TreeNode node1 = PackTreeNodeUtil.pack(tree,root,
                        new TreeNode(++id,adress.getCountry()).setValue(adress.getCountry()), checkMap);
                TreeNode node2 =PackTreeNodeUtil.pack(tree,node1,
                        new TreeNode(++id,adress.getCity()).setValue(adress.getCity()), checkMap);
                TreeNode node3 = PackTreeNodeUtil.pack(tree, node2,
                        new TreeNode(++id, adress.getRegion()).setValue(adress.getRegion()), checkMap);
                PackTreeNodeUtil.pack(tree, node3,
                        new TreeNode(++id, adress.getName()).setValue(adress.getName()), checkMap);
            }
            return tree;
        }
    }

前台:

var setting = {
		data: {
			simpleData: {
				enable: true,
				idKey: "id",
				pIdKey: "pid",
				rootPId: 0
			}
		}
	};
	zNode = ""//通过ajax获取
	$(document).ready(function(){
		$.fn.zTree.init($("#treeDemo"), setting, zNodes);
	});

前台显示:
在这里插入图片描述
此demo为精简例子,如要复用,可添加参数和前台逻辑

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值