JPA - 实体设计问题

Yat*_*oel 7 java entity entity-relationship jpa object-relationships

我正在开发Java桌面应用程序并使用JPA进行持久化.我有一个问题如下:

我有两个实体:

  • 国家

国家/地区具有以下属性:

  • 国名(PK)

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 CountryCityis OneToMany之间的关系,我countryCity类中添加了一个变量.

但是我们有重复的数据(countryName)存储在City类'对象中的两个位置:一个在country对象中,另一个在cityPK对象中.

但另一方面,两者都是必要的:

  • countryNamecityPK对象中是必要的,因为我们以这种方式实现复合主键.

  • countryNamecountry对象中是必要的,因为它是显示对象之间的关系的标准方式.

如何解决这个问题?

axt*_*avt 7

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)