开发者

How to generate a key for a group entity?

I'm trying to make a group entity. Something like:

class User {
}

class UserColor {
}

...

Key key = new KeyFactory.Builder(
  User.class.getSimpleName(), username).
    .addChild(UserColor.class.getSimpleName(), ???).getKey();

I know the unique username up-front to use for the key of the User object. But I just want app engine to generate a random unique value for the key value of the UserColor instance.

I think this is described here, but I don't understand their wording: http://code.google.com/appengine/docs/java/datastore/transactions.html

To create an object with a system-generated numeric ID and an entity group parent, you must use an entity group parent key field (such as customerKey, above). Assign the key of the parent to the parent key field, then leave the object's key field set to null. When the object is saved, the datastore populates the key field with the complete key, including the entity group parent.

and this is their example:

@Persistent
@Extension(vendorName="datanucleus", key="gae.parent-pk", value="true")
private Key customerKey;

but I don't understand - should UserColor look like this then?:

class UserColor {
    @Persistent
    @Extension(vendorName="datanucleus", key="gae.parent-pk开发者_Python百科", value="true")
    private Key mKeyParent;

    @Primary
    private Key mKey; // leave null
}

...

Key keyParent = new KeyFactory.Builder(
  User.class.getSimpleName(), username);

UserColor uc = new UserColor();
uc.setKeyParent(keyParent);
pm.makePersistent(uc); // now generated for me automatically?

is that correct? Using this method, I should be able to use a User and a UserColor object in a transaction together, right?

Thanks


correct, your second example is the right idea. it will let you use a User and its child UserColor(s) in the same transaction.

also, if the User has a key name like you mention, you should be able to run the transaction without either entity existing in the datastore beforehand. however, if the User entity will have an id-based key, you'll need to store it first so that it gets an id allocated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜