首页 > 解决方案 > 具有复合主的 JPA 实体也是同一个表的外键

问题描述

我有两个表 A 和 B。表 A 中有两列 col1 和 col2(这两列都是主键,即与 col1 和 col2 复合)。表 B 中有一列,表 A 中的两列都指向该列,即 col1 和 col2 是与表 B 中的列相关的外键。

如何为表 A 实现 JPA 实体?

谢谢

标签: jpaforeign-keyscomposite-key

解决方案


那么您可以通过以下代码实现:

@Embeddable
public class AID {
    public int xID;
    public int yId;
}

@Entity
public class A {
    @EmbeddedId
    public AID id;

    @OneToMany(mappedBy="A")
    public Collection<B> b;
}


@Entity
public class Meeting {
    @ID
    @GeneratedValue
    public Long id;

    @MapsId("aID")
    @JoinColumns({
        @JoinColumn(name="xID", referencedColumnName="xID"),
        @JoinColumn(name="yId", referencedColumnName="yId")
    })
    @ManyToOne
    public A a;
}

推荐阅读