Hibernate / JPA,保存新实体,同时仅在@OneToOne关联上设置id [英] Hibernate/JPA, save a new entity while only setting id on @OneToOne association
本文介绍了Hibernate / JPA,保存新实体,同时仅在@OneToOne关联上设置id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个实体,
class A { @OneToOne B b; }
class B { ... lots of properties and associations ... }
当我创建新A()然后保存时,我只想设置b的id。
When I create new A() and then save, i'd like to only set the id of b.
所以新A()。setB(新B()。setId(123))。
然后保存,并让数据库保持不变。
Then save that and have the database persist it.
我真的不需要或者想要首先从数据库中获取整个B,以填充A的实例。
I do not really need to or want to fetch the entire B first from the database, to populate an instance of A.
我记得以前这个曾经有用过,但是当我测试的时候不行。
I remember this used to work, but when I am testing it is not.
我也尝试过 Cascade All 。
推荐答案
B b = (B) hibernateSession.byId(B.class).getReference(b.getId());
a.setB(b);
hibernateSession.load(...) // can also be used as it does the same.
JPA等价物是:
entitymanager.getReference(B.class, id)
这篇关于Hibernate / JPA,保存新实体,同时仅在@OneToOne关联上设置id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文