2010-04-27 85 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。