创建、检索、更新和删除实体

Datastore 中的数据对象称为“实体”,其中的每个实体都会出于查询目的而归类为特定“种类”。例如,如果您要编写人力资源应用,则可以使用种类为 Employee 的实体表示每位员工。请注意,实体数据值采用属性形式。如需详细了解实体,请参阅概念文档实体、属性和键

创建实体并设置属性

在 Java 中,通过构造 Entity 类的实例并将实体的种类作为参数提供给 Entity() 构造函数,可以创建新实体。根据需要填充实体的属性后,您可以将实体作为参数传递给 DatastoreService.put() 方法,从而保存到数据存储区。您可以通过将实体的键名作为第二个参数传递给构造函数来指定键名。

以下示例会创建种类为 Employee 的实体,填充其属性值,并将其保存到数据存储区:

Entity employee = new Entity("Employee", "asalieri");
employee.setProperty("firstName", "Antonio");
employee.setProperty("lastName", "Salieri");
employee.setProperty("hireDate", new Date());
employee.setProperty("attendedHrTraining", true);

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

请注意,如果您未提供键名,Datastore 会自动为实体的键生成数字 ID:

Entity employee = new Entity("Employee");
// Set the entity properties.
// ...
datastore.put(employee);

检索实体

如需检索由给定键标识的实体,请将 Key 对象传递给 DatastoreService.get() 方法:

// Key employeeKey = ...;
Entity employee = datastore.get(employeeKey);

更新实体

如需更新现有实体,请修改实体对象的特性,然后将其传递给 DatastoreService.put() 方法。该对象数据将覆盖现有实体。每次调用 put() 时,整个对象都会发送到 Datastore。

删除实体

如果您知道实体的键,可以使用 DatastoreService.delete() 方法删除实体:

// Key employeeKey = ...;
datastore.delete(employeeKey);

批量删除实体

如果您需要删除大量实体,我们建议您使用 Dataflow 批量删除实体

使用批量操作

如果要通过单个 Datastore 调用对多个实体执行操作,可以使用批量操作。

以下是批量调用的示例:

Entity employee1 = new Entity("Employee");
Entity employee2 = new Entity("Employee");
Entity employee3 = new Entity("Employee");
// ...

List<Entity> employees = Arrays.asList(employee1, employee2, employee3);
datastore.put(employees);

这些批量操作按实体组对所有实体或键进行分组,然后对每个实体组并行执行请求的操作,这比分别为每个实体单独调用更快,因为它们仅产生一次服务调用的开销。如果批量使用多个实体组,则在服务器端对所有组并行执行该操作。

批量 put()delete() 调用可能对某些实体成功,而对另一些实体不成功。如果调用必须完全成功或完全失败,请使用事务且所有受影响的实体要归入同一实体组。