当孩子有复合PK时,如何在父实体中定义@OneToMany?

amp*_*ent 2 referential-integrity hibernate jpa composite-key

我的Parent班级有两个子班级: ChildParentHobby. Child 类有一个单一的 PK 并且@OneToMany它的映射有效。问题是我不知道如何将它映射到具有复合 PK 的 ParentHobby 类上。

家长:

//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;
Run Code Online (Sandbox Code Playgroud)

孩子:

@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;
Run Code Online (Sandbox Code Playgroud)

家长爱好:

@Entity @Table(name="PARENT_HOBBY") 公共类 ParentHobby {

@EmbeddedId
private ParentHobbyPK id;
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)

我在编译时得到的异常是:

mappedBy reference an unknown target entity property: ParentHobby.parent in Parent.hobbyList
Run Code Online (Sandbox Code Playgroud)

当子实体具有复合主键时,如何在父实体中定义 @OneToMany 关系?

相似的:

@OneToMany 与复合键的关系

当外键是复合主键的一部分时,休眠实体映射?

JPA复合键@OneToMany

Bri*_*rgh 5

You need to use a derived identity.

ParentHobbyPK should look like this:

@Embeddable
public class ParentHobbyPK {
    @Column(name="HOBBY_ID")
    private String hobbyID;
    private long parentID; // corresponds to the PK type of Parent
}
Run Code Online (Sandbox Code Playgroud)

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;

    ...
}
Run Code Online (Sandbox Code Playgroud)

派生身份在 JPA 2.1 规范的第 2.4.1 节中讨论。