How to use UpdateItemRequest in a DynamoDB transaction?

760 Views Asked by At

I have a Java Spring application, where I use DynamoDB, so far without transactions. However, I have recently come across a new use case, which requires persisting together related objects. I am new to this topic, and have therefore read about DynamoDB transactions, but cannot find a way to use the API in a proper object-oriented fashion. What am I missing?

For now, when I need to update an object, I proceed as follows, building an UpdateItemRequest:

Map<String, AttributeValueUpdate> updates = new HashMap<>();
// fill updates

Map<String, ExpectedAttributeValue> expected = new HashMap<>();
// fill expectations

UpdateItemRequest request = new UpdateItemRequest()
            .withTableName(TABLE_NAME)
            .withKey(key)
            .withAttributeUpdates(updates)
            .withExpected(expected);
dynamoDBClient.updateItem(request);

However, the documentation for building a transaction recommends the following syntax:

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

If I were to follow the documentation, then I would need to build an update expression - but what I persist can be quite complex, and this would require some heavy string manipulation, which is not satisfactory (parser to make, would be slow and prone to errors).

Is there a a way to obtain this update expression from an UpdateItemRequest? Or any recommended way to build such complex expressions, e.g. as a serialized form of something? Or even better, some object-oriented way to use transactions, passing a map of update objects rather than a big string?

Thanks.

0

There are 0 best solutions below