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

时间:2021-08-17 12:29:19

具体代码实现如下:

 @RequestMapping("getTree")
    public Map<String, Object> getTree(int id) {
        Map<String, Object> map = new HashMap<>();
        try {
            ChinaCitys province = dao.findProvince(id); //查询出一个省
            if (province != null) {
                List<ChinaCitys> 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<ChinaCitys> citys) {
        List<ChinaCitys> 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>