我的Parent
课程有两个子课程:Child
和ParentHobby
。 Child类具有单个PK,并且@OneToMany
映射有效。问题是我不知道如何在ParentHobby类上映射它,它具有复合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:
@Entity @table(名称= “PARENT_HOBBY”) 公共课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;
我在编译时获得的异常是:
mappedBy reference an unknown target entity property: ParentHobby.parent in Parent.hobbyList
当子项具有复合主键时,如何在父实体中定义@OneToMany关系?
<子>类似:子>
@OneToMany relationship with Composite key
Hibernate Entity mapping when Foreign key is part of the composite primary key?
答案 0 :(得分:3)
您需要使用派生身份。
ParentHobbyPK
应如下所示:
@Embeddable
public class ParentHobbyPK {
@Column(name="HOBBY_ID")
private String hobbyID;
private long parentID; // corresponds to the PK type of Parent
}
ParentHobby
应该看起来像这样(重要的是@MapsId
注释):
@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节讨论了派生身份。