我有查询,当我使用 Group By 语句运行时,我得到以下格式的结果。
Country Region Town
---------------------------------------
England North NewCastle
England North Manchester
England North Leeds
England South London
England South Bristol
England South Birmingham
England South Portsmouth
Norway North Trondheim
Norway North Tromso
Norway South Oslo
Norway South Stavanger
Norway West Bergen
结果返回一个 JPA 对象列表,如下所示
@Entity
@Indexed
@Table(name="Country")
public class Country extends AbstractDomainObject {
private static final long serialVersionUID = 8619373591913330663L;
private String country;
private String region;
private String town
@Id
@Column(name="COUNTRY")
public Long getCountry() {
return batchNumber;
}
public void setCountry(String country) {
this.country = country;
}
@Id
@Column(name="REGION")
public Date getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
@Id
@Column(name="TOWN")
public String getTown() {
return description;
}
public void setTown(String town) {
this.description = description;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
我必须遍历 JPA 对象列表并创建新对象。我似乎无法获得循环结构。我花了太多时间试图做到这一点,所以我想知道是否有更好、更简单的方法来做到这一点。我想要实现的是将数据存储在以下类型的集合中:
class CountryTowns{
String Country;
List<Region> regions;
//getters and setters
}
class Region{
String region;
List<String> towns;
//getters and setters;
}
要将数据存储在上面显示的对象中,我试图遍历数据并在 Country 或 Town 发生变化时创建对象,但我似乎无法正确处理。
List<CountryTowns> countryTowns = new ArrayList();
List<Country> countries = dataServicesFacade.getListOfCountries();
boolean firstIteration = false;
for(Country country : countries){
if (firstIteration){
CountryTowns countryTowns = new CountryTowns;
Region region = new Region;
}
if(prevCountry.equals(country.getCountry())){
if(prevRegion.equals(country.getRegion())){
region.setRegion(countryGetRegion())
region.towns.add(country.getTown());
}else{
countryTowns.regions.add(region);
Region region = new Region();
}
}else{
CountryTowns countryTowns = new CountryTowns;
}
prevCountry = country.getCountry();
prevRegion = country.getRegion();
}
对于比上面显示的列多得多的列表,它很快就会变得混乱。您将如何解决上述问题,是否有推荐的方法或设计模式可以更轻松地遍历列表?