How to generate a key for a group entity?

Posted by user246114 on Stack Overflow See other posts from Stack Overflow or by user246114
Published on 2010-04-27T02:19:02Z Indexed on 2010/04/27 2:23 UTC
Read the original article Hit count: 316

Filed under:

Hi,

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", 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

© Stack Overflow or respective owner

Related posts about google-app-engine