仅当对象不存在时,DynamoDBMapper才会保存

时间:2015-03-26 19:09:18

标签: java amazon-web-services amazon-dynamodb

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

2 个答案:

答案 0 :(得分:8)

我相信您应该可以使用可以应用于映射器的DynamoDbSaveExpression对象来执行此操作。

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
}

答案 1 :(得分:3)

以下是使用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);

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

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

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

通过单元测试:

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