1

我有一个非常简单的项目,有 3 个类:

@Entity
@Table(name = "A", uniqueConstraints = {})
@org.hibernate.annotations.Table(appliesTo = "A", indexes = {})
@SecondaryTable(name = "C", pkJoinColumns {@PrimaryKeyJoinColumn(columnDefinition = "A_ID", name = "A_ID")})
public class Machine
{
    @Id
    @GeneratedValue
    @Column(name = "A_ID", nullable = false)
    private Integer id;

    @Column(name = "a1", nullable = false)
    private Integer a1;

    @Column(name = "c1", table = "C", nullable = false)
    private Integer c1;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "A_B", joinColumns = {@JoinColumn(name = "A_ID")}, inverseJoinColumns = {@JoinColumn(name = "B_ID")})
    private List<B> bs = new ArrayList<B>();

}

@Entity
@Table(name = "B")
@SecondaryTable(name = "A_B", pkJoinColumns = {@PrimaryKeyJoinColumn(columnDefinition = "B_ID", name = "B_ID")})
@org.hibernate.annotations.Table(appliesTo = "B")
public class B {

    @Id
    @GeneratedValue
    @Column(name = "B_ID", nullable = false)
    private Integer id;

    @Column(name = "B_1", nullable = false)
    private Integer b1;

    @Embedded
    @AttributeOverrides({
@AttributeOverride(name = "d1", column = @Column(name = "D_1", table = "A_B")),
@AttributeOverride(name = "d2", column = @Column(name = "D_2", table = "datastore_assignment"))})
    private final D d = new D();

    }

@Embeddable
public class D
{
    private long d1;

    private long d2;
}

将一个具有两个 BI 的 A 实例插入到会话中时,会期望这样:

A_B table
A_ID   B_ID   D_1   D_2
   1      1     1     1
   1      2     1     1

但事情是这样的:

A_B table
A_ID   B_ID   D_1   D_2
   1      1     0     0
   1      2     0     0
   1   NULL     1     1
   1   NULL     1     1

任何的想法?

谢谢!

问候。

塞达诺。

4

1 回答 1

2

问题是 A 不知道 D_1 和 D_2 并且不插入它们。并且hibernate不关心链接表和辅助表是否相同,并在保存B时将D_1 / D_2插入其中。要解决这个问题:

添加 inverse 告诉 A 它不应该插入 A_B 因为它不知道 D_1 和 D_2

@ManyToMany(fetch = FetchType.LAZY, mappedBy = ...)
@JoinTable(name = "A_B", joinColumns = {@JoinColumn(name = "A_ID")}, inverseJoinColumns = {@JoinColumn(name = "B_ID")})
private List<B> bs = new ArrayList<B>();

并在 B 中映射对 A 的引用

@ManyToOne(name = "B_1", nullable = false, table = "A_B")
private A a;

确保你设置

a.getBs().Add(b);
b.setA(a);
于 2012-05-31T12:06:03.890 回答