如果您有一个像这样的表:
|--------|------------|
| 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;
}
什么是最好的方法? 谢谢。