JPA アノテーションと休止状態を使用して、最近、次のような一方向の onetomany マッピングの問題に遭遇しました。
@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)
null 許容の場合、hibernate は更新によって FK を設定するのに、null 許容でない場合は挿入で設定するのはなぜですか?