Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/amazon-web-services/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 仅当对象不';不存在_Java_Amazon Web Services_Amazon Dynamodb - Fatal编程技术网

Java 仅当对象不';不存在

Java 仅当对象不';不存在,java,amazon-web-services,amazon-dynamodb,Java,Amazon Web Services,Amazon Dynamodb,使用Java DynamoDBMapper,如何仅在对象不存在(基于主键)的情况下保存该对象。如果它确实存在,我希望抛出异常或失败,而不是更新现有条目。我相信您应该能够使用可以应用于映射器的对象来实现这一点 AWS网站上有一个教程,代码如下所示: try { DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression(); Map expected = new HashMap(); ex

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

我相信您应该能够使用可以应用于映射器的对象来实现这一点

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

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
}

以下是使用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);
资料来源:

编辑:下面是我在实践中对它的实现。极易实施:

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

请参见withExists(false)是否应该?在(“准备就绪”)之后缺少一个括号,这是正确的行:expected.put(“状态”),new ExpectedAttributeValue(new AttributeValue(“准备就绪”)。withExists(true))-1因为此答案仅在表中已存在项时保存。这与问题所需的结果相反。更改为修复布尔状态(oops)编辑了答案,因为在使用
时。withExists(false)
不得提供值。