@ManyToMany在连接表和英国使用二度关系的JPA关系

时间:2015-07-28 11:13:57

标签: java hibernate jpa many-to-many hibernate-mapping

我有这个实体模型(简化):

@Entity
class A {
  @Id
  String id;

  Collection<B> bs;
}

@Entity
class B {
  @Id
  String id;

  @ManyToOne
  @JoinColumn(name = "c_id", nullable = false)
  C c;
}

@Entity
class C {
  @Id
  String id;
}

在A和B之间添加连接表(多对多关系)的最佳方法是什么,并使用A.id和B.c.id强制执行复合UK?

我试过这样的事情:

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable
        (name = "a_b",
                joinColumns = @JoinColumn(name = "a_id"),
                inverseJoinColumns = {
                        @JoinColumn(name = "b_id", referencedColumnName = "id"),
                        @JoinColumn(name = "c_id", referencedColumnName = "c_id")},
                uniqueConstraints = @UniqueConstraint(name = "uk_a_c", columnNames = {"a_id", "c_id"}))

但我得到MultipleBagFetchException,这很奇怪。它必须与c_id不是主键的一部分有关。如果我从c_id移除inverseJoinColumns,它会按预期工作,但这不是我需要的。

2 个答案:

答案 0 :(得分:1)

如果在B和C之间它是一对一的关联,你可以在这两者之间共享主键,这样

B.id = C.id = B.c.id

然后,连接表唯一键可以在A.id和B.id之间。

答案 1 :(得分:0)

我的最终映射如下所示:

@Entity
@EntityListeners(ABListener.class)
@Table(name = "a_b", uniqueConstraints =
@UniqueConstraint(name = "uk_rel_a_b", columnNames = {"a_id", "c_id"}))
public class AB extends BaseEntity<Long> {

    private Long id;

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

    @ManyToOne(optional = false)
    @JoinColumn(name = "b_id")
    private B b;

    @ManyToOne(optional = false)
    @JoinColumn(name = "c_id")
    private C c;

    public AB(A a, B b) {
        this.a = a;
        this.b = b;
    }
    /* rest of the class */
}

是一个处理C的设置的听众:

public class ABListener {

    @PrePersist
    @PreUpdate
    void handleCUpdate(AB ab) {
        if (ab.getB() != null) {
            ab.setC(ab.getB().getC());
        }
    }

}