2016-07-07 41 views
5

我有一個更新DynamoDB項目的Java函數。我想處理由於某種原因更新不成功的情況。我的代碼如下所示:如何在使用Java SDK的dynamoDB中更新或插入是否成功?

Table table = dynamoDB.getTable(tableName); 
AttributeUpdate att = new attributeUpdate(fieldName).put(value); 
UpdateItemOutcome outcome = table.updateItem(keyFieldName, keyValue, att); 

updateItem調用的結果是UpdateItemOutcome對象。所有這些都是一個getItem()方法,它應該提供update操作返回的屬性,以及一個提供UpdateItemResult對象的getUpdateItemResult()方法。

即使調用成功,getItem()仍然爲空。 UpdateItemResult對象似乎沒有任何方法爲我提供有關操作的任何狀態或錯誤。

有誰知道在DynamoDB中檢查這種操作的結果的最佳做法是什麼?這個問題也適用於putItem()操作。

謝謝!

回答

3

在文檔:http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html

Use ReturnValues if you want to get the item attributes as they appeared either before or after they were updated. For UpdateItem, the valid values are: 

    NONE - If ReturnValues is not specified, or if its value is NONE, then nothing is returned. (This setting is the default for ReturnValues.) 

    ALL_OLD - If UpdateItem overwrote an attribute name-value pair, then the content of the old item is returned. 

    UPDATED_OLD - The old versions of only the updated attributes are returned. 

    ALL_NEW - All of the attributes of the new version of the item are returned. 

    UPDATED_NEW - The new versions of only the updated attributes are returned. 

There is no additional cost associated with requesting a return value aside from the small network and processing overhead of receiving a larger response. No Read Capacity Units are consumed. 

Values returned are strongly consistent 

Type: String 

Valid Values: NONE | ALL_OLD | UPDATED_OLD | ALL_NEW | UPDATED_NEW 

Required: No 

你可以這樣做:

UpdateItemSpec updateItemSpec = new UpdateItemSpec(); 
... 
updateItemSpec.withReturnValues(ReturnValue.ALL_NEW); 

然後UpdateItemOutcome將有填充字段。

但是,如果更新或put操作失敗,DynamoDB將拋出異常,因此如果您只想檢查操作是否成功,則不需要獲取返回值。

+0

謝謝,這將工作得很好。我已經開始着手捕捉異常,但這是一個完整的答案。 –