Hibernate多对多映射引用部分复合键

时间:2014-04-15 21:56:36

标签: java hibernate

我的问题就像这一个:https://forum.hibernate.org/viewtopic.php?f=1&t=1002125

我的架构中有以下表格:

  • 表A带有复合键(attr1,attr2);
  • 表格B带有pk(attr3);
  • 和表A_B,它是A和B之间的关系表,带有复合键(fk_attr1,fk_attr3),其中fk_attr1和fk_attr3分别引用字段attr1和attr2

关系中没有使用attr2。

我使用hibernate插件生成了映射java类,生成的代码如下所示:

A类

private Set<B> bs = new HashSet<B>(0);
private AId id;

@EmbeddedId
@AttributeOverrides({ @AttributeOverride(name = "attr1", column = @Column(name = "attr1", nullable = false)),
            @AttributeOverride(name = "attr2", column = @Column(name = "attr2", nullable = false)) })
public AId getId() {
    return this.id;
}

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "A_B", catalog = "my_schema", joinColumns = { @JoinColumn(name = "fk_attr1", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "fk_attr3", nullable = false, updatable = false) })
public Set<B> getBs() {
    return this.bs;
}

B类

private Set<A> as = new HashSet<A>(0);

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "A_B", catalog = "my_schema", joinColumns = { @JoinColumn(name = "fk_attr3", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "fk_attr1", nullable = false, updatable = false) })
public Set<A> getAs() {
    return this.as;
}

类AId (实体A的ID)

private String attr1;
private Long attr2;

@Column(name = "attr1", nullable = false)
public String getAttr1() {
    return this.attr1;
}

@Column(name = "attr2", nullable = false)
public Long getAttr2() {
    return this.attr2;
}

但它总是会产生这种异常:

org.hibernate.AnnotationException:从B引用A的外键具有错误的列数。应该是2

与Hibernate建立这种关系的正确方法是什么?

0 个答案:

没有答案