[英]Setting @ManyToOne or @OneToOne relationship without actually fetching the associated entity
I have entity similiar to 我有类似的实体
@Entity
@Table(name = "Template")
public class Template implements java.io.Serializable {
Script script;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SCRIPTID")
public Script getScript() {
return script;
}
public void setScript(Script script) {
this.script= script;
}
}
where Script
is another entity. 其中
Script
是另一个实体。
When I want to save Template
, I get id of Script
from some legacy code so my saving code is: 当我想保存
Template
,我从一些旧代码中获取了Script
ID,因此我的保存代码是:
Long scriptId = createNewScript(....);
Script script = commonDao.findByPrimaryKey(Script.class, scriptId); //unnecessary reading
template.setScript(script);
commonDao.save(template);
The problem is that I have to do unnecessary read the Script
only to set it in Template
. 问题是我只需要在
Template
进行设置就不必阅读Script
。 Is there any way to set only Id of script, but still have getter that returns Script
. 有什么方法可以只设置脚本的ID,但是仍然可以通过getter返回
Script
。
Yes, there is a way. 是的,有办法。
Hibernate allows you to do something like this: Hibernate允许您执行以下操作:
template.setScript(new Script());
template.getSCript().setId(scriptId);
commonDao.save(template);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.