关于无限递归的后台写法(java部分)

 案例以获取组织架构为例。组织下会存在下级组织,可无限阶层。思路很简单,首先获取所有组织结构,然后进行分组递归即可。只需要查询一次数据库。

  • 表结构

CREATE TABLE `t_sys_org` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '数据库自增',
  `parent_id` bigint(20) DEFAULT NULL COMMENT '数据库自增',
  `name` varchar(128) NOT NULL,
  `descs` varchar(255) DEFAULT NULL,
  `sn` smallint(6) DEFAULT NULL,
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `update_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`),
  KEY `parent_id` (`parent_id`),
  CONSTRAINT `t_sys_org_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `t_sys_org` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;
  • 准备工作部分

 1.表对应的实体类
  
public class TSysOrg implements Serializable {
    private Long id;

    private Long parentId;

    private String name;

    private String descs;

    private Short sn;

    private Date createTime;

    private Date updateTime;
  
    private static final long serialVersionUID = 1L;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getParentId() {
        return parentId;
    }

    public void setParentId(Long parentId) {
        this.parentId = parentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescs() {
        return descs;
    }

    public void setDescs(String descs) {
        this.descs = descs;
    }

    public Short getSn() {
        return sn;
    }

    public void setSn(Short sn) {
        this.sn = sn;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

}

 2.返回结果bo类

 

public class RspSysOrgTreesBO extends TSysOrg {


    //下级组织列表
    private List<RspSysOrgTreesBO> childOrgs;

    public List<RspSysOrgTreesBO> getChildOrgs() {
        return childOrgs;
    }

    public void setChildOrgs(List<RspSysOrgTreesBO> childOrgs) {
        this.childOrgs = childOrgs;
    }


}
  • 主体代码部分

 1.controller:
  
List<RspSysOrgTreesBO> orgs = this.sysOrgServiceImpl.getLeftTrees();
2.service:
入口方法:
public List<RspSysOrgTreesBO> getLeftTrees() throws Exception {
        //获取所有的记录
        List<TSysOrg> orgs = this.listAllSysOrg();
        if (null != orgs && orgs.size() > 0) {
            List<RspSysOrgTreesBO> allOrgs = new ArrayList<RspSysOrgTreesBO>();
            for (TSysOrg org : orgs) {
                RspSysOrgTreesBO bo = new RspSysOrgTreesBO();
                bo.setId(org.getId());
                bo.setName(org.getName());
                bo.setCreateTime(org.getCreateTime());
                bo.setDescs(org.getDescs());
                bo.setSn(org.getSn());
                bo.setParentId(org.getParentId());
                allOrgs.add(bo);
            }
            return this.getTreeOrgs(allOrgs);
        }
        return null;
    }
 获取所有组织架构数据

public List<TSysOrg> listAllSysOrg() throws Exception {
        return tSysOrgMapper.listAllOrgs();
    }

封装组织架构树状结构
public List<RspSysOrgTreesBO> getTreeOrgs(List<RspSysOrgTreesBO> allOrgs) throws Exception {
        List<RspSysOrgTreesBO> listParentRecord = new ArrayList<RspSysOrgTreesBO>();
        List<RspSysOrgTreesBO> listNotParentRecord = new ArrayList<RspSysOrgTreesBO>();
        // 第一步:遍历allOrgs找出所有的根节点和非根节点
        if (allOrgs != null && allOrgs.size() > 0) {
            for (RspSysOrgTreesBO org : allOrgs) {
                if (null == org.getParentId()) {
                    listParentRecord.add(org);
                } else {
                    listNotParentRecord.add(org);
                }
            }
        }
        // 第二步: 递归获取所有子节点
        if (listParentRecord.size() > 0) {
            for (RspSysOrgTreesBO record : listParentRecord) {
                // 添加所有子级
                record.setChildOrgs(this.getChildOrgs(listNotParentRecord, record.getId()));
            }
        }
        return listParentRecord;
    }

 递归查询子组织
public List<RspSysOrgTreesBO> getChildOrgs(List<RspSysOrgTreesBO> childList, Long parentId) throws Exception {
        List<RspSysOrgTreesBO> listParentOrgs = new ArrayList<RspSysOrgTreesBO>();
        List<RspSysOrgTreesBO> listNotParentOrgs = new ArrayList<RspSysOrgTreesBO>();
        // 遍历childList,找出所有的根节点和非根节点
        if (childList != null && childList.size() > 0) {
            for (RspSysOrgTreesBO record : childList) {
                // 对比找出父节点
                if (record.getParentId() == parentId) {
                    listParentOrgs.add(record);
                } else {
                    listNotParentOrgs.add(record);
                }

            }
        }
        // 查询子节点
        if (listParentOrgs.size() > 0) {
            for (RspSysOrgTreesBO record : listParentOrgs) {
                // 递归查询子节点
                record.setChildOrgs(getChildOrgs(listNotParentOrgs, record.getId()));
            }
        }
        return listParentOrgs;
    }

Mapper.xml文件:
<select id="listAllOrgs" resultMap="BaseResultMap"  >
        select
         id, parent_id, name, descs, sn, create_time, update_time
        from t_sys_org
        ORDER BY parent_id ASC ,sn ASC
    </select>






无限级树(Java递归) 2007-02-08 10:26 这几天,用java写了一个无限极的树,递归写的,可能代码不够简洁,性能不够好,不过也算是练习,这几天再不断改进。前面几个小图标的判断,搞死我了。 package com.nickol.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nickol.utility.DB; public class category extends HttpServlet { /** * The doGet method of the servlet. * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println(""); out.println(""); out.println(" Category" + "" + "body{font-size:12px;}" + "" + "" + ""); out.println(" "); out.println(showCategory(0,0,new ArrayList(),"0")); out.println(" "); out.println(""); out.flush(); out.close(); } public String showCategory(int i,int n,ArrayList frontIcon,String countCurrent){ int countChild = 0; n++; String webContent = new String(); ArrayList temp = new ArrayList(); try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(n==1){ if(rs.next()){ webContent += "";//插入结尾的减号 temp.add(new Integer(0)); } webContent += " ";//插入站点图标 webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,"0"); } if(n==2){ webContent += "\n"; }else{ webContent += "\n"; } while(rs.next()){ for(int k=0;k<frontIcon.size();k++){ int iconStatic = ((Integer)frontIcon.get(k)).intValue(); if(iconStatic == 0){ webContent += "";//插入空白 }else if(iconStatic == 1){ webContent += "";//插入竖线 } } if(rs.isLast()){ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(0)); }else{ webContent += "";//插入结尾的直角 } }else{ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入未结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(1)); }else{ webContent += "";//插入三叉线 } } if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += " ";//插入文件夹图标 }else{ webContent += " ";//插入文件图标 } webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,countCurrent+countChild); countChild++; } webContent += "\n"; DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return webContent; } public boolean checkChild(int i){ boolean child = false; try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(rs.next()){ child = true; } DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return child; } } --------------------------------------------------------------------- tree.js文件 function changeState(countCurrent,countChild){ var object = document.getElementById("level" + countCurrent + countChild); if(object.style.display=='none'){ object.style.display='block'; }else{ object.style.display='none'; } var cursor = document.getElementById("cursor" + countCurrent + countChild); if(cursor.src.indexOf("images/tree_minus.gif")>=0) {cursor.src="images/tree_plus.gif";} else if(cursor.src.indexOf("images/tree_minusbottom.gif")>=0) {cursor.src="images/tree_plusbottom.gif";} else if(cursor.src.indexOf("images/tree_plus.gif")>=0) {cursor.src="images/tree_minus.gif";} else {cursor.src="images/tree_minusbottom.gif";} var folder = document.getElementById("folder" + countCurrent + countChild); if(folder.src.indexOf("images/icon_folder_channel_normal.gif")>=0){ folder.src = "images/icon_folder_channel_open.gif"; }else{ folder.src = "images/icon_folder_channel_normal.gif"; }
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值