问题描述
我正在从 UI 发送一个对象.将使用对现有子项的引用来创建此对象.
I am sending an object from UI. This object is going to be created with a reference to an existing child.
这是这种关系的简单说明.
This is simple illustration for this relation.
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:对象引用了一个未保存的瞬态实例".
When I save this object, Hibernate gives me " org.hibernate.TransientPropertyValueException: object references an unsaved transient instance ".
我不需要去救孩子,因为我根本不换孩子.只需要在父表中保存孩子的id.
I don't have to save a child as I do not change child at all. Just need to save child's id in parent's table.
我尝试使用了一些 CascadeType,但都没有奏效.
I've tried to use few CascadeType, but none of them worked.
推荐答案
只需为孩子使用代理:
parentEntity.setChild(entityManager.getReference(ChildEntity.class, childId));
这里的重点是使用 EntityManager.getReference:
获取一个实例,其状态可能会被延迟获取.
Hibernate 将创建只包含 id 而不去数据库的代理.
Hibernate will create the proxy containing only the id without going to the database.
这篇关于休眠 - 如何用分离的孩子保存父母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!