2016-08-24 43 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