2016-08-24 73 views
0

需求是更新实体中某一行的字段。但下面的代码正在更新实体行。我在哪里犯错误?GAE:JAVA-只更新实体特定行中的一个字段

//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

如果最后一行是'datastore.put(E2)'? –

+0

对不起..这是错误的是e2只... – user1742919

回答

1

您的实施没有任何问题。数据存储中的插入和更新没有区别。

从文档:

云数据存储区API 不创建新的 实体和更新现有之间进行区分。如果对象的键代表已存在的 实体,则put()方法将覆盖现有的 实体。您可以使用事务来测试在创建密钥之前是否存在具有 给定密钥的实体。

您可以参考documentation.

此外,如果你正在更新一个字段过快考虑使用内存缓存。

如果你想照顾的交易,看看:

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(); 
    } 
} 

这是记录​​

+0

那么我怎么能只更新现有的行实体的特定领域..你的意思是说它不可能 – user1742919

+1

@ user1742919你正在更新一个特定的领域。如果想要说明如何处理同一个实体行的并发写入操作,那么请查看事务。我已经更新了答案 – Atrix1987

+0

@ user1742919认为upvoting和接受答案,如果它帮助你 – Atrix1987