今天在开发的时候,写了两个方法:
方案一:
1、先获取省份,根据省份 id 去数据库查询这个省份有多少城市,这样后台就会执行多条 SQL 语句(查询所有省份一条,根据省份查询城市,有多少省份就会发出多少查询语句,这样性能开销比较大);
public List<ProvinceWithCity> getProvinceWithCityList(){
Long start = System.currentTimeMillis();
System.out.println("实现方案1计时\t" + start);
List<ProvinceWithCity> provinceWithCityList = new ArrayList<>();
ProvinceWithCity pwc = null;
List<Province> provinceList = provinceBusiness.getProvinceList();
for(Province province : provinceList){
pwc = new ProvinceWithCity();
pwc.province_id = province.getProvinceId();
pwc.name = province.getName();
pwc.cities = cityBusiness.getCityListByProvinceId(province.getProvinceId());
provinceWithCityList.add(pwc);
}
Long end = System.currentTimeMillis();
System.out.println("实现方案1计时\t" + end);
System.out.println("耗时:" + (end - start));
return provinceWithCityList;
}
2、方案二(获取所有的省份和城市信息)
步骤1:获取所有省份的信息
(重点:然后把所有的省份信息放在一个 Map 里面)
步骤2:获取所有的城市信息
步骤3:遍历所有的城市信息,如果城市信息里面的 province_id 在步骤1 的 Map 里,再在里面添加。
代码实现:
public List<ProvinceWithCity> getProvinceWithCityList(){
Long start = System.currentTimeMillis();
System.out.println("实现方案1计时\t" + start);
List<ProvinceWithCity> provinceWithCityList = new ArrayList<>();
List<Province> provinceList = provinceBusiness.getProvinceList();
List<City> cityList = cityBusiness.getCityList();
Map<Integer, ProvinceWithCity> map= new HashMap<>();
for (Province province : provinceList) {
Integer provinceId = province.getProvinceId();
ProvinceWithCity provinceWithCity = new ProvinceWithCity();
provinceWithCity.province_id = provinceId;
provinceWithCity.name = province.getName();
provinceWithCity.cities = new ArrayList<City>();
map.put(provinceId, provinceWithCity);
provinceWithCityList.add(provinceWithCity);
}
for (City city : cityList) {
Integer provinceId = city.province_id;
if (!map.containsKey(provinceId)) {
continue;
}
ProvinceWithCity provinceWithCity = map.get(provinceId);
provinceWithCity.cities.add(city);
}
Long end = System.currentTimeMillis();
System.out.println("实现方案1计时\t" + end);
System.out.println("耗时:" + (end - start));
return provinceWithCityList;
}
经测试,方案二明显效率高,因为和数据库的交互少。