AWS Developer Tools Blog

Using S3Link with Amazon DynamoDB

Today we’re excited to talk about the new S3Link class. S3Link allows you to easily link to an Amazon S3 resource in your Amazon DynamoDB data. You can use S3Link when storing Java objects in Amazon DynamoDB tables with the DynamoDBMapper class.

To use the new S3Link class, just add a member of type S3Link to your annotated class. The following User class has an S3Link member named avatar:

@DynamoDBTable(tableName = "user-table")
public class User {
    private String username;
    private S3Link avatar;

    @DynamoDBHashKey
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public S3Link getAvatar() {
        return avatar;
    }

    public void setAvatar(S3Link avatar) {
        this.avatar = avatar;
    }
}

Now that we have our POJO annotated, we’re ready to use DynamoDBMapper to work with our data. The following example shows three ways to use S3Link:

  • Upload a file to Amazon S3
  • Download a file from Amazon S3
  • Get an Amazon S3 client to perform more advanced operations
// Construct a mapper and pass in credentials to use when sending requests to Amazon S3
DynamoDBMapper mapper = new DynamoDBMapper(myDynamoClient, myCredentialsProvider);

// Create your objects
User user = new User();
user.setUsername("jamestkirk");

// Create a link to your data in Amazon S3
user.setAvatar(mapper.createS3Link(myBucketName, "avatars/jamestkirk.jpg"));
  
// Save the Amazon DynamoDB data for your object (does not write to Amazon S3)
mapper.save(user);
  
// Use S3Link to easily upload to Amazon S3
user.getAvatar().uploadFrom(new File("/path/to/all/those/user/avatars/jamestkirk.jpg"));

// Or use S3Link to easily download from Amazon S3
user = mapper.load("spock");
user.getAvatar().downloadTo(new File("/path/to/downloads/spock.jpg"));

// Or grab a full Amazon S3 client to perform more advanced operations
user.getAvatar().getAmazonS3Client();

That’s all there is to using the new S3Link class. Just point it at your data in Amazon S3, and then use the link to upload and download your data.

For more information about using DynamoDBMapper, see the Using the Object Persistence Model with Amazon DynamoDB section in the Amazon DynamoDB Developer Guide.