java 用于条件保存的 DynamoDBMapper

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28081401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:58:44  来源:igfitidea点击:

DynamoDBMapper for conditional saves

javaamazon-web-servicesamazon-dynamodb

提问by n00b

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.

我正在使用 DynamoDBMapper 并希望在且仅当 hashkey 和 range 键组合不存在时有条件地保存。我知道有一些方法可以使用 UUID 来减少碰撞的可能性,但我想通过使用条件保存来保护自己。

I came across this articlethat uses DynamoDBSaveExpressionhowever I'm not able to specify that the condition is "hashkey AND rangekey" cannot exist. The APIspecifies a withConditionalOperatormethod but I'm not able to see this in my class. I am using the latest aws java sdk also from here.

我遇到了这篇使用DynamoDBSaveExpression 的文章,但是我无法指定条件是“hashkey AND rangekey”不能存在。该API指定一个withConditionalOperator方法,但我不能看到这在我的课。我也从这里使用最新的 aws java sdk 。

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

关于如何有条件地保存的任何建议?或者我可能做错了什么?

回答by mkobit

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.

这使用public ExpectedAttributeValue(Boolean exists)构造函数,它只是在内部调用setExists.