我有一个非常简单的项目,有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实例时,我期望如下所示:
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。
发布于 2012-05-31 20:06:04
问题是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);https://stackoverflow.com/questions/10818179
复制相似问题