title: How to create a composite primary key which contains a @ManyToOne attribute as an @EmbeddedId in JPA?
body: <p><em>I'm <a href="https://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/">asking and answering my own question</a>, but i'm not assuming i have the best answer. If you have a better one, please post it!</em></p>
  <p>Related questions:</p>
  <ul>
  <li><a href="https://stackoverflow.com/questions/4634836/how-to-set-a-backreference-from-an-embeddedid-in-jpa">How to set a backreference from an @EmbeddedId in JPA</a></li>
  <li><a href="https://stackoverflow.com/questions/5550922/hibernate-mapping-where-embeddedid">hibernate mapping where embeddedid</a> (?)</li>
  <li><a href="https://stackoverflow.com/questions/3164207/jpa-compound-key-with-embeddedid">JPA Compound key with @EmbeddedId</a></li>
  </ul>
  <p>I have a pair of classes which are in a simple aggregation relationship: any instance of one owns some number of instances of the other. The owning class has some sort of primary key of its own, and the owned class has a many-to-one to this class via a corresponding foreign key. I would like the owned class to have a primary key comprising that foreign key plus some additional information.</p>
  <p>For the sake of argument, let's use those perennial favourites, Order and OrderLine.</p>
  <p>The SQL looks something like this:</p>
  <pre><code>-- 'order' may have been a poor choice of name, given that it's an SQL keyword!
  create table Order_ (
      orderId integer primary key
  );
  create table OrderLine (
      orderId integer not null references Order_,
      lineNo integer not null,
      primary key (orderId, lineNo)
  );
  </code></pre>
  <p>I would like to map this into Java using JPA. Order is trivial, and OrderLine can be handled with an @IdClass. <a href="https://gist.github.com/1171380" rel="nofollow noreferrer">Here's the code for that</a> - the code is fairly conventional, and i hope you'll forgive my idiosyncrasies.</p>
  <p>However, using @IdClass involves writing an ID class which duplicates the fields in the OrderLine. I would like to avoid that duplication, so i would like to use @EmbeddedId instead.</p>
  <p>However, a naive attempt to do this fails:</p>
  <pre><code>@Embeddable
  public class OrderLineKey {
      @ManyToOne
      private Order order;
      private int lineNo;
  }
  </code></pre>
  <p>OpenJPA rejects the use of that as an @EmbeddedId. I haven't tried other providers, but i wouldn't expect them to succeed, because the JPA specification requires that the fields making up an ID class be basic, not relationships.</p>
  <p>So, what can i do? How can i write a class whose key contains @ManyToOne relationship, but is handled as an @EmbeddedId?</p>