I'm having trouble getting the composite primary key and foreign keys working in JPA 2 / Hibernate. I am trying to create a simple scenario with countries and provinces:
Country:
@Entity
@Table(name = "country")
public class Country extends DomainObjectBase implements Serializable {
@Id
@Basic(optional = false)
@Column(name = "code")
private String code;
@Basic(optional = false)
@Column(name = "name")
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "country")
private List<Province> provinces;
}
Primary Key of the Province:
@Embeddable
public class ProvincePK implements Serializable {
@Basic(optional = false)
@Column(name = "code")
private String code;
@Basic(optional = false)
@Column(name = "country_code")
private String countryCode;
}
Provinces:
@Entity
@Table(name = "province")
public class Province extends DomainObjectBase implements Serializable {
@EmbeddedId
protected ProvincePK provincePK;
@Basic(optional = false)
@Column(name = "name")
private String name;
@MapsId("country_code")
@JoinColumn(name = "country_code", referencedColumnName = "code", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Country country;
}
This creates the right tables for me with one exception:
Country table:
Table of provinces
- code PK FK - the problem here is that it creates a foreign key link for the code column of the country table.
- country_code FK This is the only foreign key link I want
- name
/ , ? - , , !
.