Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 501
maxarndt Avatar asked Jan 31 '17 15:01

maxarndt


1 Answers

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!

like image 95
maxarndt Avatar answered Oct 09 '22 20:10

maxarndt