2010-04-27 82 views
1

我正在嘗試創建一個組實體。例如:如何爲組實體生成密鑰?

class User { 
} 

class UserColor { 
} 

... 

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

我知道唯一的用戶名前用於用戶對象的關鍵。但我只想讓應用引擎爲UserColor實例的鍵值生成隨機唯一值。

我認爲這是這裏所描述的,但我不明白他們的措辭: http://code.google.com/appengine/docs/java/datastore/transactions.html

要使用系統生成的數字ID和父實體組創建一個對象,你必須使用一個實體組父母鍵字段(如上面的customerKey)。將父項的鍵分配給父鍵字段,然後將對象的鍵字段設置爲空。保存對象時,數據存儲使用完整鍵填充鍵字段,包括實體組父鍵。

,這是他們的榜樣:

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

,但我不明白 - 應該UserColor這個樣子?:然後

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? 

是正確的?使用這種方法,我應該可以在一個事務中同時使用一個User和一個UserColor對象,對吧?

謝謝

回答

0

正確,你的第二個例子是正確的想法。它將允許您在同一個事務中使用User及其子UserColor。

此外,如果用戶具有類似於您提到的密鑰名稱,那麼您應該能夠事先在數據存儲中不存在任何實體的情況下運行事務。但是,如果用戶實體具有基於ID的密鑰,則需要先將其存儲,以便分配ID。