公司最近有个业务,一次性查询表数据后组装成树,数据结构类似如下
需要组装成树形结构
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为精简例子,如要复用,可添加参数和前台逻辑