我有下表,其中国家可以有多个州,州可以有多个城市,城市可以有多个区域,区域可以有多个街道。
数据库表:
Country { countryid, name, description }
State { stateid, name, description, countryid (FK) }
City { cityid, name, description, stateid (FK) }
Area { areaid, name, description, cityid (FK) }
Street { streetid, name, description, areaid (FK) }
用于保存值的 Java 值对象:
CountryVO { countryId, name, description, List<StateVO> }
StateVO { stateId, name, description, List<CityVO> }
CityVO { cityId, name, description, List<AreaVO> }
AreaVO { areaId, name, description, List<StreetVO> }
StreetVO { streetId, name, description }
我想使用本机选择查询获取所有记录,并根据查询结果集填充我的值对象。
选择查询
select country.id, country.name, country.description,
state.id, state.name, state.description,
city.id, city.name, city.description,
area.id, area.name, area.description,
street.id, street.name, street.description,
from Country country, State state, City city, Area area, Street street
where country.id = state.id
and state.id = city.id
and city.id = area.id
and area.id = street.id
我将使用以下代码获取结果集:
Query query = entityManager.createNativeQuery(<above_select_query>);
List<Object[]> stList = (List<Object[]>) query.getResultList();
for (Object[] objects : stList) {
// Here I will populate all my VOs based on values found in result set
}
请注意,在这里我可能会得到具有重复列值的结果集:
例如:
如果一个国家 (country-1) 有两个州 (state1, state2) 并且两个州都有两个城市 (state1-city1, state1-city2, state2-city1, state2-city2) 并且区域和街道相同。
Row1: country-1 | state1 | state1-city1
Row2: country-1 | state1 | state1-city2
Row3: country-1 | state2 | state2-city1
Row4: country-1 | state2 | state2-city2
在填充我的值对象时,我必须手动验证是否为第一行创建了 Country 对象,不应该为其余行创建它,并且对于其余值相同。
有没有更好的模式来解决这类问题?