问题描述
我的Parent
类有两个子类:Child
和ParentHobby
. Child类具有单个PK,并且其上的@OneToMany
映射有效.问题是我不知道如何将其映射到具有复合PK的ParentHobby类.
My Parent
class has two child classes: Child
and ParentHobby
. The Child class has a singular PK and the @OneToMany
mapping on it works. The problem is that I don't know how to map it on the ParentHobby class, which has a composite PK.
父母:
//this works
@OneToMany(cascade = CascadeType.ALL, mappedBy = "parent", fetch = FetchType.EAGER)
private List<Child> childList;
//this DOES NOT work
@OneToMany(cascade = CascadeType.ALL, mappedBy = "parent", fetch = FetchType.EAGER)
private List<ParentHobby> hobbyList;
孩子:
@Entity
@Table(name="CHILD")
public class Child {
@Id
@SequenceGenerator(name="CHILD_SEQ", sequenceName="CHILD_DB_SEQ", allocationSize = 1)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="CHILD_SEQ")
@Column(name="CHILD_ID")
private long childID;
@JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID", insertable = true, updatable = true)
@ManyToOne(optional = true)
private Parent parent;
ParentHobby:
@实体@Table(name ="PARENT_HOBBY")公共课程ParentHobby {
@Entity@Table(name="PARENT_HOBBY")public class ParentHobby {
@EmbeddedId
private ParentHobbyPK id;
ParentHobbyPK:
@Embeddable
public class ParentHobbyPK {
@JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID", insertable = true, updatable = true)
@ManyToOne(optional = true)
private Parent parent;
@Column(name="HOBBY_ID")
private String hobbyID;
我在编译时遇到的异常是:
The exception I get at compile time is:
mappedBy reference an unknown target entity property: ParentHobby.parent in Parent.hobbyList
当孩子具有复合主键时,如何在父实体中定义@OneToMany关系?
推荐答案
您需要使用派生身份.
ParentHobbyPK
应该看起来像这样:
@Embeddable
public class ParentHobbyPK {
@Column(name="HOBBY_ID")
private String hobbyID;
private long parentID; // corresponds to the PK type of Parent
}
ParentHobby
应该看起来像这样(重要的是@MapsId
批注):
ParentHobby
should look like this (the important thing being the @MapsId
annotation):
@Entity
@Table(name="PARENT_HOBBY")
public class ParentHobby {
@EmbeddedId
private ParentHobbyPK id;
@MapsId("parentID") // maps parentID attribute of the embedded ID
@ManyToOne(optional = true)
@JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID", insertable = true, updatable = true)
private Parent parent;
...
}
JPA 2.1规范的第2.4.1节中讨论了派生身份.
Derived identity is discussed in JPA 2.1 spec, section 2.4.1.
这篇关于当子级具有复合PK时,如何在父级实体中定义@OneToMany?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!