title: Composite primary key, foreign key. Reference to object or key?
body: <p>I have two classes <code>Foo</code> and <code>Bar</code>. The tables in the database look like this:</p>
  
  <pre><code>|Foo|
  |id : INT (PK) | bar_id : INT (PK, FK) |
  
  |Bar|
  |id : INT (PK) |
  </code></pre>
  
  <p>Normally I would map it like this:</p>
  
  <pre><code>@Entity
  public class Bar
  {
      @Id
      @Column(name = "id")
      private int id;
  
      @OneToMany
      private Set&lt;Foo&gt; foo;
  }
  
  @Entity
  public class Foo
  {
      @EmbeddedId
      private FooPK key;
  
      @MapsId("barId")
      @ManyToOne
      @JoinColumn(name = "bar_id", referencedColumnName = "id")
      private Bar bar;
  }
  
  @Embeddable
  public class FooPK
  {
      @Column(name = "id")
      private int id;
      @Column(name = "bar_id")
      private int barId;
  }
  </code></pre>
  
  <p>However the id's in <code>FooPK</code> are loosely mapped and need to be connected manually. I would prefer a solution that maps using Objects in stead of loose ids.
  I tried the following but (of course) it didn't work, but I think it gives an idea of what I would like to achieve:</p>
  
  <pre><code>@Entity
  public class Bar
  {
      @Id
      @Column(name = "id")
      private int id;
  
      @OneToMany
      private Set&lt;Foo&gt; foo;
  }
  
  @Entity
  public class Foo
  {
      @EmbeddedId
      private FooPK key;
  
      @MapsId("barId")
      @ManyToOne
      @JoinColumn(name = "bar_id", referencedColumnName = "id")
      @Access(AccessType.FIELD)
      private Bar getBar()
      {
          return key.getBar();
      }
  }
  
  @Embeddable
  public class FooPK
  {
      @Column(name = "id")
      private int id;
  
      @Transient
      private Bar bar;
  
      //....
  
      @Column(name = "bar_id")
      @Access(AccessType.PROPERTY)
      private int getBarId
      {
          return bar.getId();
      }
  }
  </code></pre>
  
  <p>Another problem with the latter solution is that the <code>getBarId()</code> method in <code>FooPK</code> needs to have a <code>setBarId(Int)</code> method. Setting the Object using the ID can be done by accessing the data access layer, however this (in my opinion) violates the separation of business/domain/data layers.</p>
  
  <p>So what to do? Go with the first solution and keep the ids in sync manually or is there another (best) practice?</p>