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;
}
上記のオブジェクトにデータを保存するために、国または町に変更があった場合にデータをループしてオブジェクトを作成しようとしていますが、正しく取得できないようです。
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();
}
上に示したものよりもはるかに多くの列を持つリストの場合、すぐに混乱する可能性があります。上記の問題をどのように解決しますか? また、リストを簡単にたどることができる推奨されるアプローチまたは設計パターンはありますか?