我有两个实体的多对一关系
@Entity(name = "foo")
public class Foo {
@Id
@Column(name = "fooId")
private Long id;
@ManyToOne(fetch = FetchType.EAGER,
targetEntity = Bar.class,
cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinColumn(name = "foo")
private Set<Bar> bars;
public Foo() {
bars = new HashSet<>();
}
public Set<Bar> getBars() {
return bars;
}
public void setBars(Set<Bar> bars) {
this.bars = bars;
}
}
@Entity(name = "bar")
public class Bar {
@Column(name = "fooId")
private Foo foo;
public Bar() {}
}
public class Persist {
@PersistenceContext(unitName = "myPersistUnit")
private EntityManager manager;
public static void main(String[] args) {
Foo f = new Foo();
f.getBars().add(new Bar());
manager.persist(f);
}
}
但是当我调用 Hibernate persist 方法时,Foo 实体已成功保存,但对于 Bar 实体,我在字段 foo 中遇到了非空违规;
有人可以告诉我我错过了什么吗?
最佳答案
您应该在 Bar Entity 中设置 Foo 实体引用。它会解决你的问题
Foo f = new Foo();
Bar bar=new Bar();
bar.setFoo(f);
f.getBars().add(bar);
manager.persist(f);
关于java - 关系表插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29334839/