title: JDO in Google App Engine: How should polymorphic relationships be implemented?
body: <p>I'm working on GAE-based applications, which uses JDO to access datastore. I need to implement polymorphic relationship between persisted objects.</p>
  
  <p>There's abstract parent class:</p>
  
  <pre><code>@PersistenceCapable
  @Inheritance(strategy = InheritanceStrategy.SUBCLASS_TABLE)
  public abstract class Parent {
   @PrimaryKey
   @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
   @Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")
   String id;
  
      // ....
  </code></pre>
  
  <p>And several child classes:</p>
  
  <pre><code>@PersistenceCapable (identityType = IdentityType.APPLICATION)
  public class Child extends Parent {
  
      // ....
  </code></pre>
  
  <p>Also, there's one more class, which should have reference to one of child classes. According to <a href="http://code.google.com/appengine/docs/java/datastore/jdo/relationships.html#Polymorphic_Relationships" rel="nofollow">"Polymorphic Relationships" section of "Entity Relationships in JDO" article</a>, the best way to implement such relationship is to store key of an object, so this class looks in the following way:</p>
  
  <pre><code>@PersistenceCapable (identityType = IdentityType.APPLICATION)
  public class OtherClass {
  
      @Persistent
      private String reference;
  
      // ....
  </code></pre>
  
  <p>I retrieve string key of referenced object from instance of OtherClass. Then I would like to obtain referenced object itself: it's an instance of one of Parent subclasses. BUT:</p>
  
  <ul>
  <li><p>If I do it with <a href="http://db.apache.org/jdo/api20/apidocs/javax/jdo/PersistenceManager.html#getObjectById%28java.lang.Object%29" rel="nofollow">pm.getObjectById(oid)</a> method:</p>
  
  <p>Object object = pm.getObjectById(reference);</p></li>
  </ul>
  
  <p>JDOObjectNotFoundException exception is thrown (<em>javax.jdo.JDOObjectNotFoundException: No such object FailedObject:...</em>).</p>
  
  <ul>
  <li><p>If I do it with <a href="http://db.apache.org/jdo/api20/apidocs/javax/jdo/PersistenceManager.html#getObjectById%28java.lang.Class,%20java.lang.Object%29" rel="nofollow">getObjectById(class, key)</a> method:</p>
  
  <p>Parent object = pm.getObjectById(Parent.class, reference);</p></li>
  </ul>
  
  <p>FatalNucleusUserException exception is thrown (<em>org.datanucleus.store.appengine.FatalNucleusUserException: Received a request to find an object of kind Parent but the provided identifier is the String representation of a Key for kind Child</em>)</p>
  
  <p>What is correct way to retrieve instance of one of subclasses referenced in another entity?</p>
  
  <p><strong>UPDATE</strong>: I found <a href="https://groups.google.com/group/google-appengine-java/browse_thread/thread/193fa626dd3f4072" rel="nofollow">this</a> thread in GAE google group, but frankly it did not help me a lot.</p>