views:

45

answers:

1

Hi,

I am reading the docs for Key generation in app engine. I'm not sure what effect using a simple String key has over a real Key. For example, when my users sign up, they must supply a unique username:

class User {
   /** Key type = unencoded string. */
   @PrimaryKey
   private String name;
}

now if I understand the docs correctly, I should still be able to generate named keys and entity groups using this, right?:

// Find an instance of this entity:
User user = pm.findObjectById(User.class, "myusername");

// Create a new obj and put it in same entity group:
Key key = new KeyFactory.Builder(
  User.class.getSimpleName(), "myusername")
    .addChild(Goat.class.getSimpleName(), "baa").getKey();
Goat goat = new Goat();
goat.setKey(key);
pm.makePersistent(goat);

the Goat instance should now be in the same entity group as that User, right? I mean there's no problem with leaving the User's primary key as just the raw String?

Is there a performance benefit to using a Key though? Should I update to:

class User {
   /** Key type = unencoded string. */
   @PrimaryKey
   private Key key;
}

// Generate like:
Key key = KeyFactory.createKey(
    User.class.getSimpleName(), 
    "myusername");
user.setKey(key);

it's almost the same thing, I'd still just be generating the Key using the unique username anyway,

Thanks

+1  A: 

When you specify a string key as you are in your example, you're specifying a key name (see the docs). As such, you shouldn't be using the KeyFactory - simply set the key field as 'myusername'.

There's no performance difference between the two options, though: Internally they are stored identically; the key name is just easier to use if you're not using parent entities for this model.

Nick Johnson
I see now, thank you.