我从EF的JPA开始,并尝试在孩子具有复合密钥的地方进行简单的主从插入。
foo插入正确(没有错误,Hibernate只是将插入内容打印到Foo语句中),但是该栏被忽略了。我发现this question在键中定义了关系,但我也无法使它起作用(与原始解决方案相同的问题,没有例外,也没有子插入)。
我的代码当前看起来像这样:
@Entity
public class Foo {
@Id
private String fooID;
@OneToMany(mappedBy = "foo")
private List<Bar> bars = new ArrayList<>();
// getter, setter,...
}
@Entity
public class Bar {
@EmbeddedId
private BarId id;
public Bar(){
this.id = new BarId();
}
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@MapsId("fooID")
@JoinColumn(name = "fooID", referencedColumnName = "fooID")
private Foo foo;
public void setFooId(String fooId){
this.id.setFooId(fooId);
}
public void setBarNo(int barNo){
this.id.setBarNo(barNo);
}
// other getter, setter,...
}
@Embeddable
public class BarId implements Serializable {
private String fooID;
private int barNo;
// getter, setter, hashCode, equals,...
}
// ...
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
Foo newFoo = new Foo();
newFoo.setFooID("baz");
Bar newBar = new Bar();
newBar.setFooId(newFoo.getFooId()); // even necessary?
newBar.setBarNo(1);
newBar.setFoo(newFoo);
newFoo.getBars().add(newBar);
em.persist(newFoo);
em.getTransaction().commit();
如果有什么区别,我将在Hibernate 5.4中使用JPA 2.2。
为了更好地说明我的追求(对于每个懂一点EF的人:]
foo.HasKey(f => f.FooID);
foo.HasMany(f => f.Bars).WithOne(b => b.Foo).HasForeignKey(b => b.FooID);
bar.HasKey(b => new {b.FooID, b.BarNo});
我必须进行哪些更改才能使其正常工作?还是我一开始使用JPA完全错误?
弄清楚了:cascade = CascadeType.PERSIST
必须放在关系的主端而不是细节侧,例如:
@OneToMany(mappedBy = "foo", cascade = CascadeType.PERSIST)
private List<Bar> bars = new ArrayList<>();