title: Access sibling data from data model
body: <p>In my Java Application, I persist the entire state of my Application via JPA. Therefore, I have a root <code>Data</code> class, which contains relations to other data objects, like <code>Settings</code> or <code>Metadata</code>:</p>
  
  <pre><code>@Entity
  @Access(AccessType.FIELD)
  public class Data {
  
      @Id
      @GeneratedValue
      private long id;
  
      @OneToOne(cascade = ALL)
      public Settings settings;
  
      @OneToOne(cascade = ALL)
      public Metadata metadata;
  
      // etc
  }
  </code></pre>
  
  <p>To save/load the state, I simply store the <code>Data</code> root instance in a DB, which is saved to and loaded from a file. Therefore, I always have one instance of <code>Data</code> with one respective instance of <code>Settings</code>, etc.</p>
  
  <p>Deep down in my data model, I have a class <code>Result</code>, which looks somewhat like this:</p>
  
  <pre><code>@Entity
  @Access(AccessType.FIELD)
  public class Result {
  
      @Id
      @GeneratedValue
      private long id;
  
      public int value;
  
      // etc
  }
  </code></pre>
  
  <p>Now in this <code>Result</code> class, I need to access the currently loaded <code>Settings</code> instance. But since the instance of <code>Result</code> is created by JPA, I don't have a reference to anything but its related data models available. </p>
  
  <p>How can I best give every <code>Result</code> instance access to this <code>Settings</code> instance?</p>
  
  <p>My ideas so far:</p>
  
  <p>1) Store the currently loaded <code>Data</code> object in a static variable, and access the <code>Settings</code> instance through it. This is bad for obvious reasons.</p>
  
  <p>2) Make each data model class reference the respective owner, up until the <code>Data</code> root class. However, this would mean having to traverse the entire data model up to the root object, just to be able to access it's children. Additionally, it would mean an additional field in each object.</p>
  
  <p>3) Use Dependency Injection (Google Guice?) to somehow inject the correct <code>Settings</code> instance where it's needed. I've never used Dependency Injection before, though, is this a good approach?</p>
  
  <p>Do I perhaps have to change my entire approach?</p>
  
  <p>Any suggestions and opinions are appreciated.</p>