使用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
当前回答
当我在标记为@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);
}
为了解决这个问题,我在创建新实体之前执行了查询。
其他回答
错误的一个可能原因是父实体的值设置不存在;例如,对于部门员工关系,为了修复错误,您必须编写以下内容:
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);
我的问题与JUnit的@BeforeEach有关。即使我保存了相关实体(在我的例子中是@ManyToOne),我也得到了同样的错误。
这个问题在某种程度上与我在父母身上的顺序有关。如果我将值赋给该属性,问题就解决了。
前任。如果我的实体问题可以有一些类别(一个或多个),并且实体问题有一个序列:
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "feedbackSeq")
@Id
private Long id;
我必须分配值问题.setId(1L);
您应该在集合映射中包含cascade=“all”(如果使用xml)或cascade=CascadeType.all(如果使用注释)。
发生这种情况是因为实体中有一个集合,而该集合中有一项或多项不在数据库中。通过指定上述选项,您可以告诉hibernate在保存父对象时将其保存到数据库中。
我刚刚收到这个错误,因为我在保存之前设置了一个未代理的实体而不是另一个实体。
我应该链接一个代理实体实例。
参见以下说明:
Child saved = childRepository.save(child);
// INCORRECT
parent.setChild(child); // <-- 'child' is NOT managed (not proxied)
// CORRECT
parent.setChild(saved); // <-- 'saved' is managed (proxied)
除了所有其他好的答案之外,如果您使用merge来持久化一个对象,并且意外地忘记在父类中使用该对象的合并引用,那么可能会发生这种情况。考虑以下示例
merge(A);
B.setA(A);
persist(B);
在这种情况下,您合并了A,但忘记了使用A的合并对象。为了解决这个问题,您必须像这样重写代码。
A=merge(A);//difference is here
B.setA(A);
persist(B);