如何修复 Hibernate“对象引用未保存的瞬态实例 - 在刷新之前保存瞬态实例”错误

新手上路,请多包涵

使用 Hibernate 保存对象时收到以下错误

object references an unsaved transient instance - save the transient instance before flushing

原文由 Tushar Ahirrao 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

您应该在集合映射中包含 cascade="all" (如果使用 xml)或 cascade=CascadeType.ALL (如果使用注释)。

发生这种情况是因为您的实体中有一个集合,并且该集合具有一个或多个数据库中不存在的项目。通过指定上述选项,您可以告诉 hibernate 在保存它们的父对象时将它们保存到数据库中。

原文由 Bozho 发布,翻译遵循 CC BY-SA 2.5 许可协议

我相信这可能只是重复回答,但为了澄清,我在 @OneToOne 映射以及 @OneToMany 上得到了这个。在这两种情况下,事实是我添加到 Child 的对象 Parent 尚未保存在数据库中。 So when I added the Child to the Parent , then saved the Parent , Hibernate would toss the "object references an unsaved transient instance - save the transient instance before flushing" message when saving the Parent.

添加 cascade = {CascadeType.ALL}Parent's 参考 Child 解决了这两种情况下的问题。这保存了 ChildParent

抱歉重复回答,只是想为大家进一步澄清。

 @OneToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "performancelog_id")
public PerformanceLog getPerformanceLog() {
    return performanceLog;
}

原文由 McDonald Noland 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题