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 l开发者_开发技巧onger works. How do I uniquely identify an object?
Article article = (Article)pm.getObjectById(KeyFactory.createKey(Article.class.getName(), id));
Any help much appreciated!
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 addChild
s 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.
精彩评论