小编典典

Hibernate-如何与orphan一起保存Parent

hibernate

我正在从UI发送对象。将使用对现有子项的引用来创建该对象。

这是这种关系的简单说明。

class ParentEntity {
    @Id
    Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    private ChildEntity child;
}

class ChildEntity {
    @Id
    Long id;
}



ChildEntity child = new ChildEntity();
child.setId(1);
//parentEntity is created based on data sent from UI
parentEntity.setChild(child);

保存该对象时,Hibernate给我“
org.hibernate.TransientPropertyValueException:对象引用了一个未保存的瞬态实例”。

我根本不需要改变孩子,所以不必拯救孩子。只需要将孩子的ID保存在父母的表中。

我尝试使用一些CascadeType,但没有一个起作用。


阅读 266

收藏
2020-06-20

共1个答案

小编典典

只需为孩子使用代理:

parentEntity.setChild(entityManager.getReference(ChildEntity.class, childId));

这里的重点是使用EntityManager.getReference

获取一个实例,其状态可能会延迟获取。

Hibernate将创建仅包含ID的代理,而无需访问数据库。

2020-06-20