java DynamoDBMapper 仅在对象不存在时才保存

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29286907/
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 14:59:46  来源:igfitidea点击:

DynamoDBMapper save only if object doesn't exist

javaamazon-web-servicesamazon-dynamodb

提问by Nosrettap

Using the Java DynamoDBMapper, how can I save an object only if it doesn't already exist (based on primary key). If it does exist, I want an exception or failure to be thrown, rather than having the existing entry updated.

使用 Java DynamoDBMapper,如何仅在对象不存在(基于主键)时才保存该对象。如果确实存在,我希望抛出异常或失败,而不是更新现有条目。

回答by tddmonkey

I believe you should be able to do this with a DynamoDbSaveExpressionobject that can apply to the mapper.

我相信您应该能够使用可以应用于映射器的DynamoDbSaveExpression对象来做到这一点。

There's a tutorial on the AWS site here, code shown below:

AWS 站点上有一个教程here,代码如下所示:

try {
    DynamoDBSaveExpression saveExpression = new       DynamoDBSaveExpression();
    Map expected = new HashMap();
    expected.put("status", new ExpectedAttributeValue().withExists(false));

    saveExpression.setExpected(expected);

    mapper.save(obj, saveExpression);
} catch (ConditionalCheckFailedException e) {
    // This means our save wasn't recorded, since our constraint wasn't met
    // If this happens, the worker can simply look for a new task to work on
}

回答by anon58192932

Here's the correct way to implement this with the DynamoDBMapper:

以下是使用 DynamoDBMapper 实现此功能的正确方法:

User newUser = new User();
newUser.setUsername(username);
newUser.setPassword(password);

DynamoDBSaveExpression saveExpr = new DynamoDBSaveExpression();
saveExpr.setExpected(new ImmutableMap.Builder()
.put("username", new ExpectedAttributeValue(false)).build());

dynamoDBMapper.save(newUser, saveExpr);

Source: https://blog.jayway.com/2013/08/24/create-entity-if-not-exists-in-dynamodb-from-java/

来源:https: //blog.jayway.com/2013/08/24/create-entity-if-not-exists-in-dynamodb-from-java/

EDIT: Here's my implementation of it in practice. Extremely easy to implement:

编辑:这是我在实践中的实现。非常容易实施:

public Statement saveIfNotExist(Statement statement) throws ConditionalCheckFailedException {
    return mapper.save(statement, new DynamoDBSaveExpression().withExpected(ImmutableMap.of("id", new ExpectedAttributeValue(false))));
}

with passing unit test:

通过单元测试:

@Test(expectedExceptions = ConditionalCheckFailedException.class)
public void shouldNotProcessIdenticalStatementUpdateInstances() {
    Statement statement1 = StatementTestBuilder.valid().build();
    Statement statement2 = StatementTestBuilder.valid().withId(statement1.getId()).build();

    statementRepository.saveIfNotExist(statement1);
    statementRepository.saveIfNotExist(statement2);
}