全国地址省市区街道,4级联动查询

在公司做项目时,遇到了这么一个需求:需要省市区街道地址下拉,所以研究了一下

1.首先,实体类设计

省表

市表

区表

街道表

2.service层

    /**
     * 获取省的数据
     * @return
     */
    public List<Province> queryProvince(RestRequest request) {
        return  areaMapper.selectProvince();
    }
    /**
     * 获取市的数据
     * @return
     */

    public List<City> getCity(String provinceCode ) {
        return  areaMapper.selectCityByProvinceId(provinceCode);
    }
   /**
     * 获取区的数据
     * @return
     */
    public List<Area> queryArea(String cityCode) {
        return areaMapper.selectAreaByCityId(cityCode);
    }
    /**
     * 获取街道的数据
     * @return
     */
    @Override
    public List<Street> getStreet(String areaCode) {
        return  areaMapper.selectStreetByAreaId(areaCode);
    }

 获取级联地址的方法

 public List<Province> queryArea(RestRequest request){
     //获取省的数据
     List<Province> provinces = getProvince();
     List<Province> provinceList = new ArrayList<>();
     for (Province province : provinces) {
         Province province1 = new Province();
         province1.setProvinceId(province.getProvinceId());
         province1.setAddress(province.getAddress());
         province1.setProvinceCode(province.getProvinceCode());


         //获取市的数据
         List<City> cities = getCity(province.getProvinceCode());
         List<City> cityList = new ArrayList<>();
         for (City city : cities) {
             City city1 = new City();
             city1.setCityId(city.getCityId());
             city1.setAddress(city.getAddress());
             city1.setProvinceCode(city.getProvinceCode());
             city1.setCityCode(city.getCityCode());

             //获取区的数据
             List<Area> areas = getArea(city.getCityCode());
             List<Area> areaList = new ArrayList<>();
             for (Area area:areas){
                 Area area1 = new Area();
                 area1.setAreaCode(area.getAreaCode());
                 area1.setAreaId(area.getAreaId());
                 area1.setAddress(area.getAddress());
                 area1.setCityCode(area.getCityCode());

                 //获取街道的数据
                 List<Street> streets =getStreet(area.getAreaCode());
                 area1.setChildren(streets);
                 areaList.add(area1);

             }
             city1.setChildren(areaList);
             cityList.add(city1);
         }
         province1.setChildren(cityList);
         provinceList.add(province1);
     }
        String jsonString = JSON.toJSONString(provinceList);
        return provinceList;
 }

3.结果返回

版权声明:本文为liunianshishui_原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/liunianshishui_/article/details/105834527