我的Parent班级有两个子班级: Child和ParentHobby。Child类具有单个PK,并且其@OneToMany上的映射有效。问题是我不知道如何将其映射到具有复合PK的ParentHobby类。
Parent
Child
ParentHobby
@OneToMany
上级:
//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;
家长爱好:
@Entity @Table(name =“ 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关系?
您需要使用派生身份。
ParentHobbyPK 应该看起来像这样:
ParentHobbyPK
@Embeddable public class ParentHobbyPK { @Column(name="HOBBY_ID") private String hobbyID; private long parentID; // corresponds to the PK type of Parent }
ParentHobby应该看起来像这样(重要的是@MapsId注释):
@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节中讨论。