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

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

当前回答

我刚刚收到这个错误,因为我在保存之前设置了一个未代理的实体而不是另一个实体。

我应该链接一个代理实体实例。

参见以下说明:

Child saved = childRepository.save(child);

// INCORRECT
parent.setChild(child);  // <-- 'child' is NOT managed (not proxied)

// CORRECT
parent.setChild(saved);  // <-- 'saved' is managed (proxied)

其他回答

另一个可能的原因是:在我的案例中,我试图在一个全新的实体上,先救孩子,再救父母。

User.java模型中的代码如下:

this.lastName = lastName;
this.isAdmin = isAdmin;
this.accountStatus = "Active";
this.setNewPassword(password);
this.timeJoin = new Date();
create();

setNewPassword()方法创建PasswordHistory记录,并将其添加到User中的历史记录集合中。由于尚未为父级执行create()语句,因此它试图保存到尚未创建的实体集合中。我所要做的就是在调用create()之后移动setNewPassword()调用。

this.lastName = lastName;
this.isAdmin = isAdmin;
this.accountStatus = "Active";
this.timeJoin = new Date();
create();
this.setNewPassword(password);

或者,如果你想使用最小的“权力”(例如,如果你不想级联删除)来实现你想要的,使用

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

...

@Cascade({CascadeType.SAVE_UPDATE})
private Set<Child> children;

案例1:当我试图创建一个父级并将该父级引用保存到其子级,然后再保存其他DELETE/UPDATE查询(JPQL)时,我遇到了这个异常。所以我只在创建父实体之后和使用相同的父引用创建子实体之后,刷新()新创建的实体。这对我有用。

案例2:

父类

public class Reference implements Serializable {

    @Id
    @Column(precision=20, scale=0)
    private BigInteger id;

    @Temporal(TemporalType.TIMESTAMP)
    private Date modifiedOn;

    @OneToOne(mappedBy="reference")
    private ReferenceAdditionalDetails refAddDetails;
    . 
    .
    .
}

子类:

public class ReferenceAdditionalDetails implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @OneToOne
    @JoinColumn(name="reference",referencedColumnName="id")
    private Reference reference;

    private String preferedSector1;
    private String preferedSector2;
    .
    .

}

在上述情况下,父级(Reference)和子级(ReferenceAdditionalDetails)具有OneToOne关系,并且当您尝试创建Reference实体,然后创建其子级(Reference AdditionalDetails)时,它将给您提供相同的异常。因此,为了避免异常,必须为子类设置null,然后创建父类。(示例代码)

.
.
reference.setRefAddDetails(null);
reference = referenceDao.create(reference);
entityManager.flush();
.
.

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

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

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