要求是更新实体中某个行的字段。但是下面的代码正在更新实体行。我在哪里弄错了?
//Inserting
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
//Util.getKey() always returns current Date
Key ky=KeyFactory.createKey("Routine", Util.getKey());
Entity e = new Entity("Routine",ky);
e.setProperty("running", Constants.RUNNING_INCREDIBLE);
datastore.put(e);
//Updating
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Key ky=KeyFactory.createKey("Routine", Util.getKey());
Entity e2=datastore.get(ky);
e2.setProperty("bAS", Constants.BAS_INCREDIBLE);
datastore.put(e);
答案 0 :(得分:1)
您的实施没有任何问题。数据存储区中的插入和更新之间没有区别。
来自文档:
Cloud Datastore API 不区分创建新 实体并更新现有实体。如果对象的键代表一个 已经存在的实体,put()方法会覆盖现有的 实体。您可以使用事务来测试具有的实体是否具有 在创建之前存在给定密钥。
您可以参考documentation.
此外,如果您要快速更新字段,请考虑使用MemCache。
如果您想处理交易,请查看:
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Transaction txn = datastore.beginTransaction();
try {
Key employeeKey = KeyFactory.createKey("Employee", "Joe");
Entity employee = datastore.get(employeeKey);
employee.setProperty("vacationDays", 10);
datastore.put(txn, employee);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
记录在案here