5

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?

shwetap
  • 621
  • 1
  • 6
  • 14

1 Answers1

9

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));
Horatiu Jeflea
  • 7,256
  • 6
  • 38
  • 67
  • 1
    Thank you. This solves my problem. The only thing is, DynamoDBMapperConfig constructor is deprecated so I used this syntax. dynamoDBMapper.save(geo, SaveBehavior.UPDATE_SKIP_NULL_ATTRIBUTES.config()); I have one more doubt, is there any way to load certain attributes while retrieving data from DB using DynamDBMapper? – shwetap Mar 04 '20 at 18:16