JPA - 实体设计问题

我正在开发Java桌面应用程序并使用JPA进行持久化。我有一个问题如下: 我有两个实体: 国家 市 国家/地区具有以下属性: 国名(PK) City具有以下属性: 城市名称 现在因为在两个不同的国家/地区可以有两个同名的城市,因此数据库中的City表的primaryKey是由
CityName
CountryName
组成的复合主键。   现在我的问题是如何在Java中实现
City
的主键作为
Entity
   @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
变量。 但是我们有重复的数据(
countryName
)存储在
City
class'对象的两个位置:一个在
country
对象中,另一个在
cityPK
对象中。 但另一方面,两者都是必要的:
cityPK
cityPK
对象中是必要的,因为我们以这种方式实现复合主键。
country
country
对象中是必要的,因为它是显示对象之间关系的标准方式。 如何解决这个问题?     
已邀请:
CityPK
中的
countryName
应使用
@Column(insertable = false, updatable = false)
标记为只读,并且两个
countryName
s应映射到同一列(使用
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;
   }
    
IMO处理此类问题的正确方法是使用生成的内部(通常为
Long
)ID而不是自然主键 - 这可以消除整个问题。当然,这需要修改您的数据库架构,但是从您的帖子我认为这是可能的。
@Entity
public class City implements Serializable {
    private Long id;

    private String name;
    private Country country;

    @Id
    @GeneratedValue
    @Column(name = "CITY_ID")
    public Long getId() {
        return this.id;
    }
    private void setId(Long id) {
        this.id = id;
    }

    // more getters, setters and annotations
}
    

要回复问题请先登录注册