Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DynamoDBMapper for conditional saves

I'm using DynamoDBMapper and would like to conditionally save if and only if the hashkey and range key combination does not exist. I know there are ways to use UUIDs to reduce the possibility of a collision but I would like to protect myself by using conditional saves.

I came across this article that uses DynamoDBSaveExpression however I'm not able to specify that the condition is "hashkey AND rangekey" cannot exist. The API specifies a withConditionalOperator method but I'm not able to see this in my class. I am using the latest aws java sdk also from here.

Any suggestions on how to conditionally save? Or what I may be doing incorrectly?

like image 814
n00b Avatar asked Jan 22 '15 04:01

n00b


People also ask

What is optimistic locking in DynamoDB?

Optimistic locking is a strategy to ensure that the client-side item that you are updating (or deleting) is the same as the item in Amazon DynamoDB. If you use this strategy, your database writes are protected from being overwritten by the writes of others, and vice versa.

Does JPA support DynamoDB?

Maven Dependencies Add the following dependencies to start working with DynamoDB using Spring Data: Spring Data JPA. AWS Java SDK DynamoDB.

What is DynamoDBMapperConfig?

public class DynamoDBMapperConfig extends Object. Immutable configuration object for service call behavior. An instance of this configuration is supplied to every DynamoDBMapper at construction; if not provided explicitly, DEFAULT is used.

Does DynamoDB support locking?

The DynamoDB Lock Client implements a protocol allowing similar applications to take advisory locks on any part of your problem domain, big or small. This protocol ensures your players “stay in possession of the ball” for a certain period of time. For a new lock, the lock client stores a lock item in the lock table.


1 Answers

DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression();
Map<String, ExpectedAttributeValue> expectedAttributes = 
    ImmutableMap.<String, ExpectedAttributeValue>builder()
        .put("hashKey", new ExpectedAttributeValue(false))
        .put("rangeKey", new ExpectedAttributeValue(false))
        .build();
saveExpression.setExpected(expectedAttributes);
saveExpression.setConditionalOperator(ConditionalOperator.AND);
try {
    dynamoDBMapper.save(objectToSave, saveExpression);
} catch (ConditionalCheckFailedException e) {
    //Handle conditional check
}

This uses the public ExpectedAttributeValue(Boolean exists) constructor, which just internally calls setExists.

like image 148
mkobit Avatar answered Sep 29 '22 14:09

mkobit