使用Hibernate保存对象时收到以下错误
object references an unsaved transient instance - save the transient instance before flushing
使用Hibernate保存对象时收到以下错误
object references an unsaved transient instance - save the transient instance before flushing
当前回答
我的问题与JUnit的@BeforeEach有关。即使我保存了相关实体(在我的例子中是@ManyToOne),我也得到了同样的错误。
这个问题在某种程度上与我在父母身上的顺序有关。如果我将值赋给该属性,问题就解决了。
前任。如果我的实体问题可以有一些类别(一个或多个),并且实体问题有一个序列:
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "feedbackSeq")
@Id
private Long id;
我必须分配值问题.setId(1L);
其他回答
在我的例子中,这是由于双向关系的@ManyToOne一侧没有CascadeType导致的。更准确地说,我在@OneToMany端有CascadeType.ALL,而在@ManyToOne端没有。将CascadeType.ALL添加到@ManyToOne解决了该问题。一对多:
@OneToMany(cascade = CascadeType.ALL, mappedBy="globalConfig", orphanRemoval = true)
private Set<GlobalConfigScope>gcScopeSet;
多对一(导致问题)
@ManyToOne
@JoinColumn(name="global_config_id")
private GlobalConfig globalConfig;
多对一(通过添加CascadeType.PERSIST修复)
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name="global_config_id")
private GlobalConfig globalConfig;
错误的一个可能原因是父实体的值设置不存在;例如,对于部门员工关系,为了修复错误,您必须编写以下内容:
Department dept = (Department)session.load(Department.class, dept_code); // dept_code is from the jsp form which you get in the controller with @RequestParam String department
employee.setDepartment(dept);
我相信这可能只是重复答案,但为了澄清,我在@OneToOne映射和@OneToMany上得到了这个答案。在这两种情况下,我添加到Parent的Child对象尚未保存在数据库中。因此,当我将Child添加到Parent,然后保存Parent时,Hibernate会在保存Parent之前抛出“对象引用未保存的瞬态实例-在刷新之前保存瞬态实例”消息。
在父级对子级的引用上添加cascade={CascadeType.ALL}解决了这两种情况下的问题。这保存了子对象和父对象。
很抱歉有重复的回答,只是想进一步澄清一下。
@OneToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "performancelog_id")
public PerformanceLog getPerformanceLog() {
return performanceLog;
}
如果您的集合可以为null,请尝试:object.SetYouColaction(null);
为完整起见:A
org.hibernate.TransientPropertyValueException
带有消息
object references an unsaved transient instance - save the transient instance before flushing
当您试图持久化/合并一个实体并引用另一个恰好分离的实体时,也会发生这种情况。