JPA - Entity design problem

后端 未结 2 1706
难免孤独
难免孤独 2020-12-06 02:55

I am developing a Java Desktop Application and using JPA for persistence. I have a problem mentioned below:

I have two entities:

  • Country
  • City<
相关标签:
2条回答
  • 2020-12-06 03:41

    IMO the proper way to deal with such issues would be to use a generated internal (typically Long) ID instead of a natural primary key - this eliminates the whole problem. Of course, this requires a modification of your DB schema, but from your post I assume that this is possible.

    @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
    }
    
    0 讨论(0)
  • 2020-12-06 03:46

    countryName in CityPK should be marked read-only using @Column(insertable = false, updatable = false) and both countryNames 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;
       }
    
    0 讨论(0)
提交回复
热议问题