I am developing a Java Desktop Application and using JPA for persistence. I have a problem mentioned below:
I have two entities:
- Country
- City
Country has the following attribute:
- CountryName (PK)
City has the following attribute:
- CityName
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
.
Now my question is How to implement the primary key of the
City
as anEntity
in 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;
}
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.
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
object is necessary because we implement composite primary keys in this way.countryName
incountry
object is necessary because it is the standard way of showing relashionship between objects.
How to get around this problem?