java递归查询省市区树形结构

具体代码实现如下:

 @RequestMapping("getTree")
    public Map getTree(int id) {
        Map map = new HashMap<>();
        try {
            ChinaCitys province = dao.findProvince(id); //查询出一个省
            if (province != null) {
                List citys = dao.findChildren(province.getId());//查询省下面的所有市
                digui(citys); //调用递归算法查询市以下的区县
                province.setChildren(citys);
            }
            map.put("data", province);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public void digui(List citys) {
        List retList = new ArrayList<>();
        for (ChinaCitys c : citys) {
            retList = dao.findChildren(c.getId());
            if (retList.size() > 0) {
                c.setChildren(retList);
                digui(retList); //循环调用自己
            }
        }
    }

sql语句:

<select id="findProvince" parameterType="java.lang.Integer" resultMap="BaseResultMap">
             select id,name from china_citys
             WHERE id = #{id}
    select>

    <select id="findChildren" parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select id,name  from china_citys
        WHERE upid = #{id}
    select>

 

转载于:https://www.cnblogs.com/superjie/p/11138438.html

你可能感兴趣的:(java,python,数据库)