如何处理表的外键到多个表主键的映射?

时间:2017-11-21 15:59:41

标签: java postgresql hibernate jpa jpa-2.0

我有3张桌子:

MainTable,Dependent1,Dependent2。

MainTable外键(DependentPK)是Table Dependent1和Dependent1的主键。 从MainTable到Dependent1和MainTable与Dependent2之间存在一对一的关系。

MainTable:

@Embeddable
@EqualsAndHashCode
@Getter
@Setter
public class DependentPK implements Serializable {

    public DependentPK() {}


    public DependentPK(String field1, String field2) {
        this.field1 = field1;
        this.field2 = field2;
    }


    @Column(name = "field1", nullable = false)
    private String field1;

    @Column(name = "field1", nullable = false)
    private String field1;
}

DependentPK(主键):

@Entity
@Table(name = "dependent1")
@Getter
@Setter
public class Dependent1 implements Serializable {

    @EmbeddedId
    private DependentPK id;

    @Column(name = "modified_by")
    private String modifiedBy;

}

Dependent1表:

@Entity
@Table(name = "dependent2")
@Getter
@Setter
public class Dependent2 implements Serializable {

    @EmbeddedId
    private DependentPK id;

    @Column(name = "name")
    private String name;

}

Dependent2表:

        var existingbody = document.getElementById('PulseBody');
        var newBody = document.createElement('tbody');
       var row = document.createElement('tr');
        row.style.height = "20px";
        row.style.verticalAlign = "middle";
        row.style.display = "table";

        var greenLight = document.createElement("img");
        greenLight.src = myPath + "/Images/GreenSquare.jpg";
        greenLight.style.height = "30px";
        greenLight.style.width = "30px";

        var cellImg = document.createElement('td');
        cellImg.appendChild(greenLight);
        row.appendChild(cellImg);

        var cellImg2 = document.createElement('td');
        cellImg2.appendChild(greenLight);
        row.appendChild(cellImg2);

        newBody.appendChild(row);

        existingbody.innerHTML = newBody.innerHTML;

以上示例仅用于描述问题。 我无法更改数据库约束和表,因为它是生产数据库。

我的问题是如何在这种情况下使用一对一映射注释?
因为相同的复合键(2列的组合)作为引用Dependent1和Dependent2表主键的外键。

1 个答案:

答案 0 :(得分:0)

您只能定义两个实体之间的关系,而不能定义实体和主键之间的关系。

了解这一点,有两种主要方法可以解决您的问题:

  1. <formats> <format>tar.gz</format> <format>tar.bz2</format> <format>zip</format> </formats> 中的Dependent1Dependent2建立关系:
  2.  
    MainTable
    1. 如果您只需要@OneToOne @JoinColumn(name = "dependent1_id") private Dependent1 dependent1; @OneToOne @JoinColumn(name = "dependent2_id") private Dependent2 dependent2; Dependent1,那么您应该考虑使用某种inheritance for entities。然后,您与Dependent2建立单一关系,DependentParentDependent1都会从中继承。