具有复合键的双向一对多关联

时间:2021-05-01 16:37:47

标签: hibernate jpa orm spring-data-jpa

我有两张桌子 A (id)B (a_id, b_id)

其中 A-B 是双向一对多关联, 并且 B 有一个复合主键 (a_id, b_id),其中 a_id 是引用 A 的 id 的外键。

我目前的尝试如下(使用 @IdClass):


@Entity(name = "A")
public class A {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @OneToMany(mappedBy = "a",
            cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
    private List<B> b = new ArrayList<>();


... constructors/getters/setters
}

@Entity(name = "B")
public class B {

    @ManyToOne
    @JoinColumn(name = "a_id")
    @MapsId("a_id")
    private A a;

    @javax.persistence.Id
    @Column(name = "b_id")
    private int bId;

    @Data
    public static class Id implements Serializable {
        private int aId;
        private int bId;
    }

... constructors/getters/setters
}

然后抛出异常:Property of @IdClass not found in entity B: aId

使用 JPA (spring-data-jpa/hibernate) 对这种与复合键的双向一对多关联进行建模的正确方法是什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

检查 Hibernate ORM 文档 for a detailed explanation of this type of mapping with @IdClass

@Entity(name = "B")
@IdClass(BPK.class)
public class B {

    @javax.persistence.Id
    @ManyToOne
    @JoinColumn(name = "a_id")
    private A a;

    @javax.persistence.Id
    @Column(name = "b_id")
    private int bId;

... constructors/getters/setters
}

public class BPK implements Serializable {
    private A a;

    private int bId;

... constructors/getters/setters
}

@MapsId has another purpose:用于 *-to-one 关联与关联实体具有相同 id 的情况。