JPA - 实体设计问题 [英] JPA - Entity design problem
问题描述
我正在开发Java桌面应用程序并使用JPA进行持久化。我有一个问题如下:
I am developing a Java Desktop Application and using JPA for persistence. I have a problem mentioned below:
我有两个实体:
- 国家
- 城市
国家/地区具有以下属性:
Country has the following attribute:
- CountryName(PK)
City具有以下属性:
City has the following attribute:
- CityName
现在可以有两个城市在两个不同的国家/地区,同名,数据库中的City表的primaryKey是一个复合主键,由 CityName
和 CountryName
。
Now as there can be two cities with same name in two different countries, the primaryKey for City table in the datbase is a composite primary key composed of CityName
and CountryName
.
现在我的问题是如何实现
City的主键
作为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 <的关系/ code>到
城市
是 OneToMany
并在上面的代码中显示这种关系,我添加了一个 country
City
类中的变量。
Now as we know that the relationship from Country
to City
is OneToMany
and to show this relationship in the above code, I have added a country
variable in City
class.
但是接下来我们将重复数据( countryName
)存储在 City
class'对象中的两个位置:<$ c $中的一个c> country 对象和 cityPK
对象中的其他对象。
But then we have duplicate data(countryName
) stored in two places in the City
class' object: one in the country
object and other in the cityPK
object.
但另一方面手,都是必要的:
But on the other hand, both are necessary:
-
countryName
incityPK
对象是必要的,因为我们以这种方式实现复合主键。
countryName
incityPK
object is necessary because we implement composite primary keys in this way.
countryName
in country
对象是必要的,因为它是显示对象之间关系的标准方式。
countryName
in country
object is necessary because it is the standard way of showing relashionship between objects.
如何解决这个问题?
推荐答案
countryName
in CityPK
应使用 @Column标记为只读(insertable = false,updatable = false )
并且 countryName
s应该映射到同一列(使用 name
属性) :
countryName
in CityPK
should be marked read-only using @Column(insertable = false, updatable = false)
and both countryName
s should be mapped to the same column (using name
property):
@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;
}
这篇关于JPA - 实体设计问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!