Skip to content
Advertisement

DynamoDB Update Transaction Java

I’m trying to update my table in dynamo with an update transaction. I want to update a specific row if it is found. If it isn’t found I want to add a new row to the table. I found some sample Java code here: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/transaction-example.html

final String PRODUCT_TABLE_NAME = "ProductCatalog";
final String PRODUCT_PARTITION_KEY = "ProductId";
HashMap<String, AttributeValue> productItemKey = new HashMap<>();
productItemKey.put(PRODUCT_PARTITION_KEY, new AttributeValue(productKey));

Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
expressionAttributeValues.put(":new_status", new AttributeValue("SOLD"));
expressionAttributeValues.put(":expected_status", new AttributeValue("IN_STOCK"));

Update markItemSold = new Update()
    .withTableName(PRODUCT_TABLE_NAME)
    .withKey(productItemKey)
    .withUpdateExpression("SET ProductStatus = :new_status")
    .withExpressionAttributeValues(expressionAttributeValues)
    .withConditionExpression("ProductStatus = :expected_status")
    .withReturnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD);

From my understanding this code is updating the row IF the condition that the product status is currently set to IN_STOCK is true and not updating it otherwise. In my code I want to see if a partition key value exists and update the row. If it doesn’t exist I want to add a new row. How would I do that?

Advertisement

Answer

In your case, you want to update the item if it exists, if not you want to create it. This is the default behaviour of UpdateItem. You don’t need to set any conditions.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement