2
我有代碼:休眠:在合併parentEntity childEntity空ID
modifiedParentEntity.addChild(newChildEntity);
session.merge(modifiedParentEntity);
newChildEntity.getId(); // == 0!!!
凡母公司擁有子實體與CascadeType.ALL
集合:
@Entity
public class ParentEntity {
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinColumn(name = "parent_entity_id")
private List<ChildEntity> childEntities;
}
問:
- 爲什麼在之後chidEntity有
0
id? - 如何以Hibernate將ID設置爲
chidEntity
的方式同時保存modifiedParentEntity
和chidEntity
?
附::
我使用postgres和序列來生成實體的ID。
我使用手動刷新模式,所以我不能在處理方法中間使用'flush'。我可以通過在合併父實體之前添加'session.save(newChildEntity)'來解決這個問題。 –
好的。在你的情況下,最好在合併父代之前讓孩子管理。在上面的樣式中,如果你沒有使用flush,那麼只有在事務完成後,孩子纔會被設置爲id。 –