JAVA查询树结构数据(省市区)使用hutool工具实现
代码:
@PostMapping("/getTree") public Object getTree() { // 查询数据 List<LxhpArea> areaList = areaService.list(); // 构建的整个树数据 List<TreeNode<String>> treeNodeList = areaList.stream().map(area -> { // 扩展字段赋值,下面要取这里的值 Map<String, Object> extraMap = new HashMap<>(); extraMap.put("domain", area.getDomain()); extraMap.put("isOpen", area.getIsOpen()); extraMap.put("bigArea", area.getBigArea()); // 单个树数据构建 TreeNode<String> treeNode = new TreeNode<String>() .setId(String.valueOf(area.getId())) // 主键 .setParentId(String.valueOf(area.getReid())) // 父节点ID .setName(area.getName()) // 省份名称 .setWeight(area.getSortOrder()) //权重,排序 .setExtra(extraMap); // 扩展字段 return treeNode; }).collect(Collectors.toList()); // 配置 TreeNodeConfig treeNodeConfig = new TreeNodeConfig(); // 自定义属性名(修改默认名称) treeNodeConfig.setWeightKey("sortOrder"); treeNodeConfig.setChildrenKey("childrenNode"); // 最大递归深度 treeNodeConfig.setDeep(1); //转换器 List<Tree<String>> treeNodes = TreeUtil.build(treeNodeList, "1", treeNodeConfig, (treeNode, tree) -> { // 给树节点赋值(还能set 父 或子节点树) tree.setId(treeNode.getId()); tree.setParentId(treeNode.getParentId()); tree.setWeight(treeNode.getWeight()); tree.setName(treeNode.getName()); // 扩展属性值赋值 // treeNode.getExtra().getOrDefault("domain", null) 是获取上面Map放进去的值,没有就是 null tree.putExtra("domain", treeNode.getExtra().getOrDefault("domain", null)); tree.putExtra("isOpen", treeNode.getExtra().getOrDefault("isOpen", null)); tree.putExtra("bigArea", treeNode.getExtra().getOrDefault("bigArea", null)); }); return JSONUtil.parse(treeNodes); }
表结构:
CREATE TABLE `lxhp_area` ( `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `reid` smallint(5) unsigned NOT NULL DEFAULT '0', `name` varchar(120) NOT NULL DEFAULT '', `sort_order` smallint(5) unsigned NOT NULL DEFAULT '0', `is_open` tinyint(3) unsigned NOT NULL DEFAULT '0', `domain` varchar(10) NOT NULL, `big_area` int(4) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=3433 DEFAULT CHARSET=utf8;
数据结构:
官方文档:https://hutool.cn/docs/#/core/%E8%AF%AD%E8%A8%80%E7%89%B9%E6%80%A7/%E6%A0%91%E7%BB%93%E6%9E%84/%E6%A0%91%E7%BB%93%E6%9E%84%E5%B7%A5%E5%85%B7-TreeUtil