Search code examples
amazon-dynamodbaws-sdkamazon-dynamodb-local

Update specific attributes with DynamoDBMapper in java


I want to update only the specific attributes of the item using DynamoDBMapper. For example, I have a User table with attributes viz., id, name, address.

@Data
@DynamoDBTable(tableName = "Users")
public class User {

    @DynamoDBHashKey
    @DynamoDBGeneratedUuid(DynamoDBAutoGenerateStrategy.CREATE)
    private String id;

    @DynamoDBAttribute
    private String name;

    @DynamoDBAttribute
    private Address address;

}

I want to update only the address attribute and not the other fields (selective update).

I could find a sample example by using UpdateItemSpec but couldn't find it for DynamoDBMapper. With UpdateItemSpec, I can use withUpdateExpression() to define update expression. More details can be found here.

Is there any way, to achieve the same with DynamoDBMapper?


Solution

  • Use the UPDATE_SKIP_NULL_ATTRIBUTES SaveBehavior

    More details on: https://aws.amazon.com/blogs/developer/using-the-savebehavior-configuration-for-the-dynamodbmapper/

    Add the SaveBehavior to your save operation and keep fields other than id and address null:

    mapper.save(user, new DynamoDBMapperConfig(SaveBehavior.UPDATE_SKIP_NULL_ATTRIBUTES));