2010-04-28 117 views
2

我正在閱讀應用程序引擎中的密鑰生成文檔。我不確定使用簡單的字符串鍵會對真正的鍵產生什麼影響。例如,當我的用戶註冊,他們必須提供一個唯一的用戶名:使用未編碼密鑰與真實密鑰,好處?

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

現在如果我理解正確的文檔,我還是應該能夠生成使用此命名鍵和實體組,右?:

// 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); 

山羊實例現在應該是相同的實體組作爲用戶,對不對?我的意思是把用戶的主鍵只留作原始字符串沒有問題?

儘管使用密鑰有沒有性能優勢?我應該更新:

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

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

它幾乎同樣的事情,我仍然只是採用獨特的用戶名無論如何生成密鑰,

感謝

回答

3

當你指定一個字符串鍵,可以在你的例子中,你正在指定一個鍵名(見the docs)。因此,您不應該使用KeyFactory - 只需將關鍵字段設置爲「myusername」即可。

儘管兩種選擇之間沒有性能差異:在內部它們的存儲方式是相同的;如果您沒有爲此模型使用父實體,則鍵名稱更易於使用。

+0

我現在看到了,謝謝。 – user246114 2010-04-29 04:37:26