使用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
当前回答
我刚刚收到这个错误,因为我在保存之前设置了一个未代理的实体而不是另一个实体。
我应该链接一个代理实体实例。
参见以下说明:
Child saved = childRepository.save(child);
// INCORRECT
parent.setChild(child); // <-- 'child' is NOT managed (not proxied)
// CORRECT
parent.setChild(saved); // <-- 'saved' is managed (proxied)
其他回答
就我而言,问题完全不同。我有两节课,比如c1和c2。C1和C2之间的依赖关系是OneToMany。现在,如果我在DB中保存C1,它将抛出上述错误。
解决这个问题的方法是从消费者请求中获取第一个C2的id,然后通过存储库调用找到C2。然后将C2保存到C1对象中。现在,如果我保存C1,它可以正常工作。
另一个可能的原因是:在我的案例中,我试图在一个全新的实体上,先救孩子,再救父母。
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);
当您具有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);
当我在标记为@Transactional的方法中创建了一个新实体和一个关联实体,然后在保存之前执行了一个查询时,我遇到了这个问题。前任
@Transactional
public someService() {
Entity someEntity = new Entity();
AssocaiatedEntity associatedEntity = new AssocaitedEntity();
someEntity.setAssociatedEntity(associatedEntity);
associatedEntity.setEntity(someEntity);
// Performing any query was causing hibernate to attempt to persist the new entity. It would then throw an exception
someDao.getSomething();
entityDao.create(someEntity);
}
为了解决这个问题,我在创建新实体之前执行了查询。
这不是错误的唯一原因。我刚才遇到了它,因为我的代码中有一个错别字,我相信它设置了一个已经保存的实体的值。
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;
}