title: How can I retrieve the foreign key from a JPA ManyToOne mapping without hitting the target table?
body: <p>I have the following two annotated classes that I use to build a graph:</p>
  
  <pre><code>@Entity
  @Table(name = "Edge")
  public class Edge
  {
      /* some code omitted for brevity */
  
      @ManyToOne
      @JoinColumn(name = "ixNodeFrom", nullable = false)
      private Node         _nodFrom;
  
      @ManyToOne
      @JoinColumn(name = "ixNodeTo", nullable = false)
      private Node         _nodTo;
  
      /* some code omitted for brevity */
  }
  
  @Entity
  @Table(name = "Node")
  public class Node
  {
      /* some code omitted for brevity */
  
      @OneToMany(mappedBy = "_nodTo")
      private Set&lt;Edge&gt;    _rgInbound;
  
      @OneToMany(mappedBy = "_nodFrom")
      private Set&lt;Edge&gt;    _rgOutbound;
  
      /* some code omitted for brevity */
  }
  </code></pre>
  
  <p>Now, when I build the graph, I issue two queries to fetch all rows from either table and set up the child / parent references, for which I need the ids stored in the <code>Edge</code> table.</p>
  
  <p>Because I have defined the relation between the two tables in JPA, accessing the edge object to get the two nodes' ids triggers two SQL statements per edge, when the JPA provider <strike>lazily</strike> * loads the associated nodes. Since I already have the node objects, and the ids have already been loaded from the edge table, I want to skip those queries, as they take an awfully long time for larger graphs.</p>
  
  <p>I tried adding these lines to the <code>Edge</code> class, but then my JPA provider wants me to make one mapping read-only, and I can't seem to find a way how to do that:</p>
  
  <pre><code>@Column(name = "ixNodeTo")
  private long _ixNodeTo;
  
  @Column(name = "ixNodeFrom")
  private long _ixNodeFrom;
  </code></pre>
  
  <p>I'm using Eclipselink and MySQL, if it matters.</p>
  
  <hr>
  
  <p>**The default behaviour for <code>@ManyToOne</code> actually is eager loading, see <a href="https://stackoverflow.com/a/3943372/2077">Pascal's answer</a>*</p>