mybatis获取无限极树的根节点和父节点

因工作中需要根据任意父级节点查找到树形节点下的根节点信息,所以写了下面一个demo方便自己需要时的查看以及需要的人参考

好了,我们现在来看一下这个结构图:

数据库结构如下: 

 

 当然了,我这一张表有多棵树,根据实际情况你可以自行取舍!

废话不多说,直接上代码: 

 Long rootId = Long.valueOf(0);

 //根据某节点获取所有父节点
  public List<Long> getParentList(Long pid,List<Long> parentNodeList){
    List<Station> stations =  stationService.findOrgParentByParentId(pid);
    if(!StringUtil.isEmpty(stations)){
      for (Station s : stations) {
        if(!StringUtil.isEmpty(s.getParentId())){
          parentNodeList.add(s.getParentId());
          getParentList(s.getParentId(), parentNodeList);
        } else {
          parentNodeList.add(s.getParentId());
          return parentNodeList;
        }
      }
    }
    return parentNodeList;
  }

  //根据某节点获取顶级父节点
  public Long getParentId(Long pid){
    List<Station> stations =  stationService.findOrgParentByParentId(pid);
    if(!StringUtil.isEmpty(stations)){
      for (Station s : stations) {
        if(!StringUtil.isEmpty(s.getParentId()) && s.getParentId() != 0){
          getParentId(s.getParentId());
        } else {
          this.rootId = s.getId();
          return s.getId();
        }
      }
    }
    return  this.rootId;
  }

//根据父节点获取全部子节点
    public List<Long> getChildren(Long pid,List<Long> childNodeList){
        List<Station> stations =  stationService.findOrganizationeByParentId(pid);
        if(!StringUtil.isEmpty(stations)){
            for (Station s : stations) {
                if(!StringUtil.isEmpty(s.getId())){
                    childNodeList.add(s.getId());
                    getChildren(s.getId(),childNodeList);
                }
            }
        }
        return childNodeList;
    }
   //mybatis获取父节点的sql
   <select id="findOrgParentByParentId" resultMap="BaseResultMap">
        SELECT A.* FROM sys_org A
            WHERE A.id = #{parentid}
    </select>

    //mybatis获取子节点的sql
     <select id="findOrganizationeByParentId" resultMap="BaseResultMap">
        SELECT A.* FROM sys_org A
            WHERE A.parentid = #{parentid}
    </select>

 好了,写在这里那么我们的核心方法已经贴出来了,需要的时候自己可以改一下,比如某个节点下面的所有子节点,可以存在map里面,把数据也存进去。
 

猜你喜欢

转载自blog.csdn.net/lchmyhua88/article/details/117963479