maxarndt
maxarndt

Reputation: 610

DynamoDBMapper: How to get saved item?

For a simple Java REST-API I created a save function to persist my model to a DynamoDB table.

The model uses a auto generated range key as you can see here:

@DynamoDBTable(tableName = "Events")
public class EventModel {
    private int country;
    private String id;
    // ...

    @DynamoDBHashKey
    public int getCountry() {
        return country;
    }
    public void setCountry(int country) {
        this.country = country;
    }

    @DynamoDBRangeKey
    @DynamoDBAutoGeneratedKey
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

    //...
}

Unfortunately the the DynamoDBMappers .save() method does not return anything. I want to return the created item to set the proper location header in my 201 HTTP response.

public EventModel create(EventModel event) {
    mapper.save(event);
    return null;
}

How can I make that work? Any suggestions? Of course I could generate the id on the client but I don´t want to do this because solving the potential atomicity issue needs additional logic on client- and server-side.

I´m using the aws-java-sdk-dynamodb in version 1.11.86.

Upvotes: 5

Views: 5803

Answers (2)

Shardool Mishra
Shardool Mishra

Reputation: 11

There is direct way through dynamo db mapper to get what is saved in dynamodb after put/update Approach mentioned by m4xy@ would work if you are saving with DynamoDBConfig as CLOBBER or UPDATE. If you are using UPDATE_SKIP_NULL_ATTRIBUTES, this approach won't work. If you are using mapper, you have to specifically call db again to get existing value (which might have been updated if there are multiple writers and you might get unxpected result). To ensure read that you expect you can implement locking for write such that if lock is acquired by a given thread, no other thread can write for a given key. But, this approach as a downside of slowing down your application. Alternatively, you can use dynamoDBClient that has apis to support return db values after write. https://sdk.amazonaws.com/java/api/2.0.0-preview-11/index.html?software/amazon/awssdk/services/dynamodb/DynamoDbClient.html

Upvotes: 1

maxarndt
maxarndt

Reputation: 610

Never mind, I figured out how to do it. The .save() method updates the reference of the object. After calling mapper.save(event); the id property is populated and has its value.

So the way to get it work is just:

public EventModel create(EventModel event) {
    mapper.save(event);
    return event;
}

That´s it!

Upvotes: 10

Related Questions