使用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
当前回答
就我而言,问题完全不同。我有两节课,比如c1和c2。C1和C2之间的依赖关系是OneToMany。现在,如果我在DB中保存C1,它将抛出上述错误。
解决这个问题的方法是从消费者请求中获取第一个C2的id,然后通过存储库调用找到C2。然后将C2保存到C1对象中。现在,如果我保存C1,它可以正常工作。
其他回答
当Hibernate认为需要保存与正在保存的对象关联的对象时,在保存对象时会发生这种情况。
我遇到了这个问题,不想保存对引用对象的更改,所以我希望级联类型为NONE。
诀窍是确保设置了被引用对象中的ID和VERSION,这样Hibernate就不会认为被引用对象是需要保存的新对象。这对我有用。
查看要保存的类中的所有关系,以计算关联对象(以及关联对象的关联对象),并确保在对象树的所有对象中设置了ID和VERSION。
或者,如果你想使用最小的“权力”(例如,如果你不想级联删除)来实现你想要的,使用
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
...
@Cascade({CascadeType.SAVE_UPDATE})
private Set<Child> children;
另一个可能的原因是:在我的案例中,我试图在一个全新的实体上,先救孩子,再救父母。
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);
错误的一个可能原因是父实体的值设置不存在;例如,对于部门员工关系,为了修复错误,您必须编写以下内容:
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);
如果您使用的是SpringDataJPA,那么在服务实现中添加@Transactional注释可以解决这个问题。