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

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

当前回答

这不是错误的唯一原因。我刚才遇到了它,因为我的代码中有一个错别字,我相信它设置了一个已经保存的实体的值。

X x2 = new X();
x.setXid(memberid); // Error happened here - x was a previous global entity I created earlier
Y.setX(x2);

我通过准确查找导致错误的变量(在本例中为Stringxid)发现了错误。我在保存实体并打印痕迹的整个代码块周围使用了捕获。

{
   code block that performed the operation
} catch (Exception e) {
   e.printStackTrace(); // put a break-point here and inspect the 'e'
   return ERROR;
}

其他回答

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

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

当Hibernate认为需要保存与正在保存的对象关联的对象时,在保存对象时会发生这种情况。

我遇到了这个问题,不想保存对引用对象的更改,所以我希望级联类型为NONE。

诀窍是确保设置了被引用对象中的ID和VERSION,这样Hibernate就不会认为被引用对象是需要保存的新对象。这对我有用。

查看要保存的类中的所有关系,以计算关联对象(以及关联对象的关联对象),并确保在对象树的所有对象中设置了ID和VERSION。

当您具有OneToMany关系并且尝试将子实体添加到父实体中的列表中,然后通过父实体检索此列表(在保存此父实体之前),而不保存子实体本身时,也可能发生这种情况,例如:

Child childEntity = new Child();
parentEntity.addChild(childEntity);
parentEntity.getChildren(); // I needed the retrieval for logging, but one may need it for other reasons.
parentRepository.save(parentEntity);

保存父实体时引发了错误。如果我删除了前一行中的检索,则不会抛出错误,但当然这不是解决方案。

解决方案是保存子实体并将保存的子实体添加到父实体,如下所示:

Child childEntity = new Child();
Child savedChildEntity = childRepository.save(childEntity);
parentEntity.addChild(savedChildEntity);
parentEntity.getChildren();
parentRepository.save(parentEntity);

为完整起见:A

org.hibernate.TransientPropertyValueException 

带有消息

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

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

如果您使用的是SpringDataJPA,那么在服务实现中添加@Transactional注释可以解决这个问题。