我正在阅读应用引擎中密钥生成的文档。我不确定使用简单的String键对真正的Key有什么影响。例如,当我的用户注册时,他们必须提供唯一的用户名:
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);
Goat实例现在应该与该用户位于同一个实体组中,对吗?我的意思是将用户的主键保留为原始字符串没有问题?
使用密钥是否有性能优势?我应该更新到:
class User {
/** Key type = unencoded string. */
@PrimaryKey
private Key key;
}
// Generate like:
Key key = KeyFactory.createKey(
User.class.getSimpleName(),
"myusername");
user.setKey(key);
这几乎是一样的,我仍然只是使用唯一的用户名生成密钥,
由于
答案 0 :(得分:3)
当您在示例中指定字符串键时,您将指定键名称(请参阅the docs)。因此,您不应该使用KeyFactory - 只需将关键字段设置为“myusername”。
这两个选项之间没有性能差异:在内部,它们的存储方式相同;如果你没有为这个模型使用父实体,那么关键名称就更容易使用了。