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

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

当前回答

我在持久化一个实体时遇到了这种情况,在该实体中,数据库中的现有记录对于用@Version注释的字段具有NULL值(用于乐观锁定)。将数据库中的NULL值更新为0已更正此问题。

其他回答

错误的一个可能原因是父实体的值设置不存在;例如,对于部门员工关系,为了修复错误,您必须编写以下内容:

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);

还有一种可能会在休眠状态下导致此错误。您可以将对象A的未保存引用设置为附加的实体B,并希望持久化对象C。即使在这种情况下,您也会遇到上述错误。

除了所有其他好的答案之外,如果您使用merge来持久化一个对象,并且意外地忘记在父类中使用该对象的合并引用,那么可能会发生这种情况。考虑以下示例

merge(A);
B.setA(A);
persist(B);

在这种情况下,您合并了A,但忘记了使用A的合并对象。为了解决这个问题,您必须像这样重写代码。

A=merge(A);//difference is here
B.setA(A);
persist(B);

为完整起见:A

org.hibernate.TransientPropertyValueException 

带有消息

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

当您试图持久化/合并一个实体并引用另一个恰好分离的实体时,也会发生这种情况。

我也面临同样的情况。通过在属性上方设置以下注释,可以解决提示的异常。

我面临的例外。

Exception in thread "main" java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.model.Car_OneToMany

为了克服,我使用了注释。

    @OneToMany(cascade = {CascadeType.ALL})
    @Column(name = "ListOfCarsDrivenByDriver")
    private List<Car_OneToMany> listOfCarsBeingDriven = new ArrayList<Car_OneToMany>();

Hibernate抛出异常的原因:

由于我附加到父对象的子对象此时不在数据库中,因此在控制台上引发此异常。

通过提供@OneToMany(cascade={CascadeType.ALL}),它告诉Hibernate在保存父对象时将它们保存到数据库中。