当子级具有复合PK时,如何在父级实体中定义@OneToMany? [英] How to define @OneToMany in parent entity when child has composite PK?

查看:98
本文介绍了当子级具有复合PK时,如何在父级实体中定义@OneToMany?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Parent类有两个子类:ChildParentHobby. 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关系?

类似:

@OneToMany与复合键的关系

休眠实体映射什么时候外键是组合主键的一部分?

JPA组合键@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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆