google-app-engine - 如何按键选择单个实体(低级 Java 数据存储 API)

标签 google-app-engine google-cloud-datastore

我对如何创建一个“键”对象来准确选择我的实体(“客户”)的 1 行感到有点困惑。

我的代码:

Query query = new Query("Customer");
// **** how do I have to create this key ???
Key key = KeyFactory.createKey("Customer", 1);
// ****
FilterPredicate keyFilter =  new FilterPredicate(Entity.KEY_RESERVED_PROPERTY,       FilterOperator.EQUAL, key);
query.setFilter(keyFilter);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
PreparedQuery pq = datastore.prepare(query);
Entity customer = pq.asSingleEntity();
if  (! (customer == null)) {
    log.info("OK !");
}
else {
    log.info("no customer found");
}

我的结果总是:“找不到客户”。

使用数据存储查看器(我在本地工作)我可以看到 3 行:

  • id/name = 1 email = "你的邮箱"name = "你的名字"
  • id/name = 2 email = "你的邮箱"name = "你的名字"
  • id/name = 3 email = "你的邮箱"name = "你的名字"

我想选择 id/name=1 的客户。 我试过了 : KeyFactory.createKey("客户", 1); 和 KeyFactory.createKey("客户", "你的名字");

但没有成功。

当我以编程方式对“客户”进行搜索 (asList) 并打印我看到的键值时:

  • 第 1 行键 = Customer("你的名字")/Customer(1)
  • 第 2 行键 = Customer("你的名字")/Customer(2)
  • 第 3 行键 = Customer("你的名字")/Customer(3)

键的可打印值采用以下格式:“实体(名称)/实体(id/名称)”

如何在我的代码中创建这样的键值? 在 javadoc 上我只看到:

  • createKey("种类", id)
  • createKey("种类", "名称")

其他方法需要一个祖先,我没有创建一个祖先.... 这是我为创建 3 行而执行的代码(已执行 3 次):

Key customerKey = KeyFactory.createKey("Customer", "your name");
Entity customer = new Entity("Customer", customerKey);
customer.setProperty("name", "your name");
customer.setProperty("email", "your email");
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(customer);

提前致谢!

问候

最大

换句话说,如何创建一个“toString”给出以下结果的键?

  • 代码:log.info("客户KeyFactory.keyToString = "+KeyFactory.keyToString(key));
  • 输出:信息:客户 KeyFactory.keyToString = Customer("your name")/Customer(1)

最佳答案

实体的创建不正确。 您不必自己创建 key 。 如果您使用种类和键名或 ID 参数创建实体,系统将根据种类和键名或 ID 自动创建一个键。

Entity customer = new Entity("Customer", "your name");
customer.setProperty("email", "your email");

DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(customer);

这就是创建所需实体所需的全部内容。

当您提供一种类型和一个键时,将创建一个子实体。 因此,您创建了一个名为“您的姓名”的客户,该客户是 ID 为 1 的客户。

要获得带有 key 的实体,您只需采用相同的参数来创建 key 。

Key key = KeyFactory.createKey("Customer", "your name");

我更愿意使用 get(),但我不知道你想做什么。 例如获取客户的电子邮件:

    Entity e;
    try {
        e = datastore.get(key);

        String myEmail= (String) e.getProperty("your email");

关于google-app-engine - 如何按键选择单个实体(低级 Java 数据存储 API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14368995/

相关文章:

Python/应用引擎 : Get client browser information

python - Google 管理的 VM 模块卡在重启循环中

python - 一周内在不同的间隔运行 cron

google-app-engine - App Engine 多个命名空间

java - 未使用 getById() 获取数据存储强一致性读取

google-app-engine - 通过 Google App 引擎发送 XMPP 消息的成本

java - 从 App Engine 构建缓存时如何平衡负载?

go - 使用 Go 获取 Google 的数据存储键值

java - Google App Engine 数据存储区中的参数化查询?

google-app-engine - Google 应用引擎 + Go + 数据存储 + 添加/更新/删除记录