使用 JPA 注释和休眠,我们最近遇到了一个单向单映射的问题,如下所示:
@Entity
public class FooOrder extends AbstractEntity{
@OneToMany(cascade= CascadeType.ALL,orphanRemoval = true)
@JoinColumn(name = "fooOrderId")
private List<FooItem> fooItems = new ArrayList<FooItem>();
public void addFooItem(foo item properties here)
{
fooItems.add(fooItem);
}
}
@Entity
public class FooItem extends AbstractEntity {
SomeRandomStuffButNoLinkToParent
}
测试代码基本上是这样的:
FooOrder fooOrder = new FooOrder(stuff here);
fooOrder.addFooItem(foo item properties here);
fooOrder = fooOrderRepository.save(fooOrder);
当我们对此运行测试时,我们会得到如下所示的 sql:
insert FooOrder(columns here)
insert FooItem(columns here missing the FK to FooOrder)
update FooItem set FooOrderFK to proper key.
但如果我设置@JoinColumn(name = "activeOrderId", nullable = false)
然后我的 sql 看起来像这样:
insert FooOrder(columns here)
insert FooItem(columns here with FK to FooOrder)
为什么hibernate在可以为空的情况下通过更新设置FK,但在不可为空的情况下将其设置在插入中?