views:

20

answers:

1

I am just learning JDO and GAE, and have gotten myself very stuck on this.

I have gone from having just

public class Article {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;
    ...
}

To now also having a parent:

public class ArticleCollection {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;
    private long count
    private Set<Article> articles;
}

However after doing this, the following code to fetch an article by id no longer works. How do I uniquely identify an object?

Article article = (Article)pm.getObjectById(KeyFactory.createKey(Article.class.getName(), id));

Any help much appreciated!

+1  A: 

A child's key includes information about its parent. You need to use a KeyFactory method that includes the parent ID.

createKey(Key parent, java.lang.String kind, long id)
          Creates a new Key with the provided parent from its kind and ID.

Check out the javadoc for more details. There is also a Builder class for convenience that lets you do something like:

Key key = new Builder("ArticleCollection", 123).addChild("Article", 1424).getKey();

That form becomes more useful as your hierarchy grows deeper, because you can chain a bunch of addChilds together before calling getKey.

If you don't know the parent of an article, I think you're stuck doing a GQL query rather than a get by key.

Peter Recore
Thanks, I couldn't find this info anywhere!!! +1
Jacob