树形结构数据
应用场景
比如我们需要构建菜单、机构树、其他业务类型树形结构
工具类
- 我们可以把菜单列表返回,获取parent_id字段等于0的节点,称为根节点,这样的节点代表一级菜单
- 再通过根节点的主键去寻找子菜单,因为要有多及菜单,所以要用递归构建子树,直到没有子菜单为止
- 最后通过构建完整的菜单树
代码示例
public class MenuTree {private final List<Menu> menuList;public MenuTree(List<Menu> menuList) {this.menuList = menuList;}/*** 获取根结点** @return*/private List<Menu> getRootNode() {List<Menu> rootNode = new ArrayList<>();menuList.forEach(item -> {if (item.getParentId() == 0) {rootNode.add(item);}});return rootNode;}/*** 构建子树** @param rootNode* @return*/private Menu builderChildrenNode(Menu rootNode) {List<Menu> childrenList = new ArrayList<>();menuList.forEach(item -> {if (Objects.equals(item.getParentId(), rootNode.getId())) {// 还需要遍历三级菜单以后的Menu menu = builderChildrenNode(item);childrenList.add(menu);}});rootNode.setChildrenList(childrenList);return rootNode;}/*** 构建树** @return*/public List<Menu> buildTree() {List<Menu> menus = getRootNode();menus.forEach(this::builderChildrenNode);return menus;}
}
返回结果示例
只展示部分数据
{"code": 0,"data": [{"id": 1,"parentId": 0,"menuName": "系统管理","menuIcon": "el-icon-setting","childrenList": [{"id": 2,"parentId": 1,"menuName": "用户管理","menuIcon": "el-icon-service","childrenList": [{"id": 3,"parentId": 2,"menuName": "查看","menuIcon": null,"childrenList": []},{"id": 4,"parentId": 2,"menuName": "新增","menuIcon": null,"childrenList": []},{"id": 5,"parentId": 2,"menuName": "修改","menuIcon": null,"childrenList": []},{"id": 6,"parentId": 2,"menuName": "删除","menuIcon": null,"childrenList": []}]}]}],"msg": "执行成功"
}
SQL
通过SQL的方式的话,只能查询出两层,如下所示:
代码示例
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="xx.tree.dao.MenuDao"><resultMap type="xx.tree.entity.Menu" id="MenuMap"><result property="id" column="id" jdbcType="INTEGER"/><result property="parentId" column="parent_id" jdbcType="INTEGER"/><result property="menuName" column="menu_name" jdbcType="VARCHAR"/><result property="menuIcon" column="menu_icon" jdbcType="VARCHAR"/><collection property="childrenList" ofType="xx.tree.entity.Menu" select="queryChildrenMenuInfo" column="id"/></resultMap><!--查询当前角色下的菜单信息--><select id="queryMenuTreeBySQL" parameterType="int" resultMap="MenuMap">select *from menuwhere parent_id = 0</select><!--子菜单查询--><select id="queryChildrenMenuInfo" parameterType="int" resultType="xx.tree.entity.Menu">select *from menuwhere parent_id = #{id}</select>
</mapper>
返回结果示例
只展示部分数据
{"code": 0,"data": [{"id": 1,"parentId": 0,"menuName": "系统管理","menuIcon": "el-icon-setting","childrenList": [{"id": 2,"parentId": 1,"menuName": "用户管理","menuIcon": "el-icon-service","childrenList": null}]}],"msg": "执行成功"
}