【问题标题】:DynamoDBMapper save only if object doesn't existDynamoDBMapper 仅在对象不存在时保存
【发布时间】:2015-03-26 19:09:18
【问题描述】:

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

【问题讨论】:

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


【解决方案1】:

我相信您应该能够使用可应用于映射器的 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
}

【讨论】:

  • 不应该是withExists(false)吗?
  • ("READY") 后面缺少括号 这是正确的行:expected.put("status", new ExpectedAttributeValue(new AttributeValue("READY")).withExists(true));
  • -1 因为此答案仅在表中已存在该项目时才保存。这与问题所期望的结果相反。
  • 更改为修复布尔状态 (oops)
  • 编辑了答案,因为使用 .withExists(false) 时不能提供值。
【解决方案2】:

这是使用 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    相关资源
    最近更新 更多