我可以使用DynamoDB Mapper删除项目而不先加载它吗?

时间:2016-01-08 20:06:03

标签: amazon-dynamodb

我使用DynamoDB mapper删除某个项目,但在删除之前必须确保它存在?

所以我现在正在做

public void delete(final String hashKey, final Long rangeKey) {
    final Object obj = mapper.load(Object.class, hashKey, rangeKey);
    if (obj != null) {
        mapper.delete(obj);
    } 
} 

如果有办法删除项目而不先加载它?如果找不到该项,我希望它静静地返回

3 个答案:

答案 0 :(得分:9)

是的,你可以!

只需创建一个包含您要删除的ID的对象,并将其作为对象传递给delete方法:

...
MyObject object = new MyObject();
object.setHashKey(hashKey);
object.setRangeKey(rangeKey);
mapper.delete(object);
....

答案 1 :(得分:2)

您也可以使用com.amazonaws.services.dynamodbv2.document.Table实例执行此操作:

table.deleteItem("hashKeyAttributeName", hashKey, "rangeKeyAttribureName", rangeKey);

要创建表的实例,您可以使用以下内容:

BasicAWSCredentials credentials = new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey); // set access and secret keys
AmazonDynamoDB amazonDynamoDB = AmazonDynamoDBClientBuilder.standard()
        .withCredentials(new AWSStaticCredentialsProvider(credentials))
        .withRegion("us-west-1") // set aws region
        .build();
Table table = new DynamoDB(amazonDynamoDB).getTable(tableName);

答案 2 :(得分:0)

只需使用DynamoDBTableMapper.deleteifExists DynamoDBTableMapper.deleteIfExists