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

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

当前回答

当我在标记为@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);
}

为了解决这个问题,我在创建新实体之前执行了查询。

其他回答

当我使用

getSession().save(object)

但当我使用

getSession().saveOrUpdate(object) 

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

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

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

我的问题与JUnit的@BeforeEach有关。即使我保存了相关实体(在我的例子中是@ManyToOne),我也得到了同样的错误。

这个问题在某种程度上与我在父母身上的顺序有关。如果我将值赋给该属性,问题就解决了。

前任。如果我的实体问题可以有一些类别(一个或多个),并且实体问题有一个序列:

@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "feedbackSeq")
@Id
private Long id;

我必须分配值问题.setId(1L);

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

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

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

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