【问题标题】:Setting @ManyToOne or @OneToOne relationship without actually fetching the associated entity设置 @ManyToOne 或 @OneToOne 关系而不实际获取关联实体
【发布时间】:2015-11-14 00:42:56
【问题描述】:

我有类似的实体

@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;
      }
}

其中Script 是另一个实体。

当我想保存 Template 时,我从一些遗留代码中获得了 Script 的 ID,所以我的保存代码是:

 Long scriptId = createNewScript(....);
 Script script = commonDao.findByPrimaryKey(Script.class, scriptId); //unnecessary reading
 template.setScript(script);

 commonDao.save(template);

问题是我必须做不必要的阅读Script 才能将其设置为Template。有没有办法只设置脚本的 ID,但仍然有返回 Script 的 getter。

【问题讨论】:

  • 我不认为有,因为 template.getScript();仅当脚本处于持久状态或存在于数据库中或您已设置它而不将其持久化到数据库时才会返回脚本我的意思是:template.setScript(script)。

标签: java database hibernate jpa orm


【解决方案1】:

是的,有办法。

Hibernate 允许您执行以下操作:

template.setScript(new Script());
template.getSCript().setId(scriptId);
commonDao.save(template);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-22
  • 2016-12-27
相关资源
最近更新 更多