JPA 2 - Foreign key that only includes one field from a composite primary key?

折月煮酒 提交于 2019-12-05 20:27:33

Try this. I've found that it works for me when I work with data models like this.

@Entity
@Table(name = "province")
@IdClass(ProvincePK.class)
public class Province extends DomainObjectBase implements Serializable {

    @Id
    @Basic(optional = false)
    @Column(name = "code")
    private String code;

    @Id
    @Basic(optional = false, insertable = false, updatable = false)
    @Column(name = "country_code")
    private String countryCode;


    @Basic(optional = false)
    @Column(name = "name")
    private String name;

    @JoinColumn(name = "country_code", referencedColumnName = "code")
    @ManyToOne
    private Country country;

}

@MapsID argument must match to the name of attribute in ProvincePK class. @JoinColumn should be marked insertable=true,updatable=true, then it works. Here is the code -

@Entity
@Table(name = "province")
public class Province  implements Serializable {

@EmbeddedId
protected ProvincePK provincePK;

@Basic(optional = false)
@Column(name = "name")
private String name;

@MapsId(value = "country_code")
@JoinColumn(name = "country_code", referencedColumnName = "code")
@ManyToOne(optional = false)
private Country country;

}

@Embeddable
public class ProvincePK implements Serializable {

@Basic(optional = false)
@Column(name = "code")
private String code;

@Basic(optional = false)
@Column(name = "country_code")
private String country_code;
}

@Entity
@Table(name = "country")
public class Country  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;
}

Hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!