Paweł Adamski
Paweł Adamski

Reputation: 3415

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.

When I want to save Template, I get id of Scriptfrom some legacy code so my saving code is:

 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. Is there any way to set only Id of script, but still have getter that returns Script.

Upvotes: 1

Views: 73

Answers (1)

Vlad Mihalcea
Vlad Mihalcea

Reputation: 153700

Yes, there is a way.

Hibernate allows you to do something like this:

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

Upvotes: 1

Related Questions