JPA与父亲和孩子的复合身份证的一对多关系

时间:2018-05-07 15:12:14

标签: java hibernate jpa one-to-many

表格:

FATHER_TABLE (PK CONF_ID, CONF_TYPE)
CONF_ID (NUMBER(2)),
CONF_TYPE(VARCHAR2(10),
... some other ininfluent columns

CHILD TABLE (PK CONF_ID, CONF_TYPE, CONF_DETAIL)
CONF_ID (NUMBER(2)),
CONF_TYPE(VARCHAR2(10),
CONF_DETAIL(NUMBER(2)),
... some other ininfluent columns

父表实体定义为:

public class FatherId implements Serializable {   
    private static final long serialVersionUID = 1L;
    private Long confId;
    private String confType;

    //equals and hashcode
}


@Entity
@IdClass(FatherId.class)
@Table(name = "FATHER_TABLE")
public class Father {
    @Id
    @Column(name = "CONF_ID")
    private Long confId;

    @Id
    @Column(name = "CONF_TYPE")
    private String confType;

    @OneToMany(mappedBy="father", fetch=FetchType.EAGER)
    private Set<Child> = new HashSet<Child>
}

如何在我的假设FatherId IdClass中或直接在ChildId实体类中引用Child

1 个答案:

答案 0 :(得分:2)

这是“衍生身份”,您可以像这样映射Child

public class ChildId implements Serializable {
    private Long confDetail; // matches the name of the attribute
    private FatherId father;  // matches name of attribute and type of Father PK
    ...
}


@Entity
@IdClass(ChildId.class)
@Table(name = "CHILD_TABLE")
public class Father {
    @Id
    @Column(name = "CONF_DETAIL")
    private Long confDetail;

    @Id
    @JoinColumns({
        @JoinColumn(name="CONF_ID", referencedColumnName="CONF_ID"),
        @JoinColumn(name="CONF_TYPE", referencedColumnName="CONF_TYPE")
    })
    @ManyToOne
    Father father;
}

在第2.4.1节的JPA 2.1规范中讨论了衍生身份(带有示例)。