I am developing a Java Desktop Application and using JPA for persistence. I have a problem mentioned below:
I have two entities:
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
}
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;
}