Yat*_*oel 7 java entity entity-relationship jpa object-relationships
我正在开发Java桌面应用程序并使用JPA进行持久化.我有一个问题如下:
我有两个实体:
国家/地区具有以下属性:
City具有以下属性:
现在因为在两个不同的国家/地区可以有两个同名的城市,因此数据库中的City表的primaryKey是由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;
}
Run Code Online (Sandbox Code Playgroud)
现在我们知道上面代码中的from Country和Cityis OneToMany之间的关系,我country在City类中添加了一个变量.
但是我们有重复的数据(countryName)存储在City类'对象中的两个位置:一个在country对象中,另一个在cityPK对象中.
但另一方面,两者都是必要的:
countryName在cityPK对象中是必要的,因为我们以这种方式实现复合主键.
countryName在country对象中是必要的,因为它是显示对象之间的关系的标准方式.
如何解决这个问题?
countryNamein CityPK应使用标记为只读,@Column(insertable = false, updatable = false)并且两个countryNames应映射到同一列(使用name属性):
@Entity
public class City implements Serializable {
@EmbeddedId
private CityPK cityPK;
@ManyToOne
@JoinColumn(name = "countryName")
private Country country;
}
@Embeddable
public class CityPK implements Serializable {
public String cityName;
@Column(name = "countryName", insertable = false, updatable = false)
public String countryName;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5228 次 |
| 最近记录: |