通过一个或多个查询从数据库获取数据?

时间:2018-11-20 14:07:18

标签: sql jdbc

如果您有一个像这样的表:

|--------|------------|
|  City  |  CountryId |
|--------|------------|

通过一个查询获取数据是否更好,例如:

public List<CityModel> selectAll() throws Exception {
    List<CityModel> cities = new ArrayList<>();

    String selectCities = "select * from cities inner join countries on countries.id = cities.countryId";

    // ... create city and country model in the same query

    return cities;
}

还是应该像这样分开:

public List<CityModel> selectAll() throws Exception {
    List<CityModel> cities = new ArrayList<>();

    String selectCities = "select * from cities";
    // ... create get cities model from table and add them to cities
    foreach(City city in cities)
    {
         String selectCountry = "select * from countries where id = " + city.getCountryId();
         // ... create country model
         city.setCountry(country)
    }
    ...
    return cities;
}

什么是最好的方法? 谢谢。

0 个答案:

没有答案