【问题标题】:How to generate a key for a group entity?如何为组实体生成密钥?
【发布时间】:2011-02-12 16:23:55
【问题描述】:

我正在尝试创建一个组实体。比如:

class User {
}

class UserColor {
}

...

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

我预先知道用于 User 对象键的唯一用户名。但我只想让应用引擎为 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 对象,对吧?

谢谢

【问题讨论】:

    标签: google-app-engine


    【解决方案1】:

    正确,您的第二个示例是正确的想法。它会让你在同一个事务中使用一个用户及其子用户颜色。

    另外,如果用户有你提到的键名,你应该能够在没有任何实体事先存在于数据存储区的情况下运行事务。但是,如果 User 实体将有一个基于 id 的键,您需要先存储它,以便它获得分配的 id。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-16
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 2018-06-24
      • 2017-10-15
      • 2013-10-21
      • 2018-12-21
      相关资源
      最近更新 更多