如何使用JPA加入表?

时间:2012-02-16 07:55:31

标签: java jpa entity

我有四张桌子。

邮编

邮编(PK)

townCode

townCode(PK)

townName

cityCode

城市

cityCode(PK)

的cityName

prefectureCode

prefectureCode(PK)

prefectureName

我希望只通过 zipCode 搜索所有参数。 现在,我写了这段代码。

@Entity
public class ZipCode extends GenericModel {
@Id
@Column(length = 7, nullable = false)
public String zipCode;
@Column(length = 8, nullable = false)
public String townCode;
@ManyToMany(targetEntity=Town.class)
@JoinTable(name="town")
@JoinColumn(referencedColumnName="townCode",insertable=true,table="town",name="townCode")
public Set<Town> towns;

@Entity
public class Town extends GenericModel {
@Id
@Column(length = 8, nullable = false)
public String townCode;
@Column(length = 255, nullable = false)
public String townName;
@Column(length = 5, nullable = false)
public String cityCode;
@ManyToMany(mappedBy="townCode")
public Set<ZipCode> zipCode;

我执行此操作,

列出zipcodes = ZipCode.find(“zipcode =?”,zipcode).fetch();

TableStatus是,

邮编 zipCode(PK)| townCode 1111111 | 123

townCode(PK)| townName | cityCode 123 |东京| 12345

我想获取所有参数,但响应只有ZipCode状态...

请告诉我,如何获取所有参数。

帮助我!

1 个答案:

答案 0 :(得分:0)

就像你已经定义了zipCode和Town之间的映射一样,你需要提供城镇之间以及城市和地区之间的映射。

一旦你完成了,你将能够获取所有城镇的邮政编码,从城镇你可以得到城市和城市,你将能够得到该县 另外看着你的表,我看不到Zipcode和Table之间的多对多关系,所以你可以考虑将它改为多对一

public class Zipcode {
// all the other attributes 
// Provide the mappings via annotation
public Town town ;

}

public class Town {
// all the other attributes 
// provide the mappings via annotation
public City city ;
}

public class City {
// all the other attributes 
// Provide the mappings via annotation
public Prefecture prefecture ;

}

public class Prefecture {
// all the other attributes 

}

最后

List zipcodes = ZipCode.find("zipcode = ? ", zipcode).fetch();
foreach(Zipcode zip : zipcodes) {
  zip.getTown() // to get the town 
  zip.getTown().getCity() // to get the city 
  zip.getTown().getCity().getPrefecture()  // to get the Prefecture 
} 

如果您不打算每次都使用所有细节,建议您选择延迟加载。