冬眠 - 如何保存父母与分离的孩子 [英] hibernate - how to save parent with detached child

查看:200
本文介绍了冬眠 - 如何保存父母与分离的孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从UI发送一个对象。该对象将通过引用现有的孩子来创建。



这个关系很简单。

  class ParentEntity { 
@Id
Long ID;

@ManyToOne(fetch = FetchType.LAZY)
私人ChildEntity子;
}

class ChildEntity {
@Id
Long id;
}



ChildEntity child = new ChildEntity();
child.setId(1);
// parentEntity根据UI
发送的数据创建。parentEntity.setChild(child);

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



我不必保存孩子,因为我根本不会更改孩子。只需要将孩子的ID保存在父表中。



我试过使用几个CascadeType,但都没有工作。

  parentEntity.setChild 

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

这里的要点是使用 EntityManager.getReference


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


Hibernate将创建只包含id的代理,而不会去数据库。


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

When I save this object, Hibernate gives me " org.hibernate.TransientPropertyValueException: object references an unsaved transient instance ".

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.

I've tried to use few CascadeType, but none of them worked.

解决方案

Just use the proxy for the child:

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

The point here is to use EntityManager.getReference:

Get an instance, whose state may be lazily fetched.

Hibernate will create the proxy containing only the id without going to the database.

这篇关于冬眠 - 如何保存父母与分离的孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆