我正在开发一个Java桌面应用程序,使用JPA进行持久化。我有以下问题:
我有两个实体:
- Country(国家)
- City(城市)
Country具有以下属性:
- CountryName(主键)
City具有以下属性:
- CityName(城市名称)
由于在两个不同的国家中可能存在两个具有相同名称的城市,因此数据库中City表的主键是由CityName
和CountryName
组成的复合主键。
现在我的问题是如何将
City
的主键作为Entity
在Java中实现
@Entity
public class Country implements Serializable {
private String countryName;
@Id
public String getCountryName() {
return this.countryName;
}
}
@Entity
public class City implements Serializable {
private CityPK cityPK;
private Country country;
@EmbeddedId
public CityPK getCityPK() {
return this.cityPK;
}
}
@Embeddable
public class CityPK implements Serializable {
public String cityName;
public String countryName;
}
现在我们知道,
Country
和City
之间的关系是OneToMany
。为了展示这种关系,我在City
类中添加了一个country
变量。但是,
City
类对象中有重复数据(countryName
)存储在两个地方:一个在country
对象中,另一个在cityPK
对象中。然而,两者都是必要的:
cityPK
对象中的countryName
是必要的,因为我们通过这种方式实现复合主键。country
对象中的countryName
是必要的,因为这是展示对象间关系的标准方式。