休眠/JPA,保存新实体,同时仅在关联@OneToOne设置 id



我有两个实体,

class A { @OneToOne B b; } 
class B { ... lots of properties and associations ... } 

当我创建新的A((然后保存时,我只想设置 b 的 id。

所以新的A((.setB(new B((.setId(123((。

然后保存它并让数据库保留它。

我真的不需要或不想先从数据库中获取整个 B,以填充 A 的实例。

我记得这曾经有效,但当我测试时它就不行了。

我也尝试过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)

下面的代码应该会有所帮助。它只会在访问 B 时获取 B。

class A { @OneToOne(fetch = FetchType.LAZY) B b; }

最新更新