Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...