【问题标题】:How to Join Table with JPA?如何使用 JPA 加入表?
【发布时间】:2012-03-07 15:04:33
【问题描述】:

我有四张桌子。

邮政编码

邮编(PK)

城镇代码

城镇

城镇代码(PK)

城镇名称

城市代码

城市

城市代码(PK)

城市名称

州代码

都道府县

地区代码(PK)

县名

我想获取仅由 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;

我执行这个,

列出邮政编码 = ZipCode.find("zipcode = ? ", zipcode).fetch();

TableStatus 是,

邮政编码 邮编(PK) |城镇代码 1111111 | 123

城镇 城镇代码(PK) |镇名 |城市代码 123 |东京 |第12345章

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

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

帮帮我!

【问题讨论】:

  • 您是否为 City 和 Prefecture 定义了实体类?你说的所有参数是什么意思?
  • 抱歉,市县尚未定义。
  • 所有参数都是 zipCode townCode townName cityCode cityName prefectureCode prefectureName 这些参数。

标签: java jpa entity


【解决方案1】:

就像您定义了 zipCode 和 Town 之间的映射一样,您需要提供 Town 和 City 之间以及 City 和 Prefecture 之间的映射。

完成此操作后,您将能够获取所有城镇的邮政编码,并且从城镇您将能够获取城市,从城市您将能够获取县 此外,查看您的表格,我看不到 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 
} 

如果您不打算每次都使用所有详细信息,建议您进行延迟加载。

【讨论】:

  • 感谢洛奇先生!!但我不明白如何使用注释...你能告诉我应该使用什么注释吗?
  • 您可以在此处阅读如何使用注解映射实体 - docs.jboss.org/hibernate/annotations/3.5/reference/en/html/… 您需要使用多对一映射
  • 非常感谢Rocky先生!!JPA对我来说太难了...在这种情况下(在ZipCode和Town之间),它是所有者?
  • Dindt 很能抓住你,你说的所有者是什么意思?
  • 抱歉,我把 OneToMany 误认为 ManyToOne。
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-16
  • 2021-11-17
相关资源
最近更新 更多