Hibernate @Embeddable行为辅助表

时间:2012-05-30 14:20:45

标签: hibernate hibernate-mapping

我有一个非常简单的项目有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;
}

当插入一个具有两个B的实例时,我会期望这样:

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

有什么想法吗?

谢谢!

问候。

ssedano。

1 个答案:

答案 0 :(得分:2)

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

添加反向告诉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);