Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically change the table accessed using DynamoDB's Java Mapper?

I have a few DynamoDB tables, all of which have entries of the same structure. I want to create a single POJO to represent all of these entries and then use DynamoDB's Mapper API to load and save those objects.

The problem is that the API requires the annotation @DynamoDBTable on my POJO. This is a compile-time annotation requires a table name parameter and so would preclude me using the POJO in a dynamic manner. DynamoDBMapperConfig seems intended to allow just such dynamic behavior changes. Unfortunately, it is not working for me: I get a client-side DDB error saying that my POJO fails validation because of the empty string I put in the annotation.

I have looked repeatedly for why my DynamoDBMapperConfig is not being respected but can't find anything. My code is below, stripped down to the essentials:

My POJO:

@DynamoDBTable(tableName = "") // table name must be overridden on each call
public class TableEntry {
    . . .
}

My client:

public class MyMapper {
    private final DynamoDBMapper mapper;
    private final DynamoDBMapperConfig configs;

    public MyMapper(String tableName) {
        AmazonDynamoDBClient client = . . .;
        mapper = new DynamoDBMapper(client);
        configs = new DynamoDBMapperConfig.Builder()
            .withTableNameOverride(TableNameOverride.withTableNameReplacement(tableName))
            .build();
    }

    . . .

    public void getEntry(String key) {
        return mapper.load(TableEntry.class, key, configs);
    }
}

When I run my code (substantially similar to what I have pasted here), I get the following message:

2 validation errors detected: Value '' at 'tableName' failed to satisfy constraint: . . .

It goes on to say that (1) the table name is too short and (2) the table name doesn't match their regex pattern.

Any suggestions why my dynamically-named tables won't work with the DynamoDB Mapper API? Documentation references are much appreciated.

[I have found where the DynamoDBMapper retrieves the table name but I haven't found any clues in there yet.]

like image 357
MonkeyWithDarts Avatar asked Apr 01 '16 03:04

MonkeyWithDarts


1 Answers

DynamoDBMapperConfig is not a static/global class. You need to pass it to the DynamoDBMapper constructor.

    AmazonDynamoDBClient client = . . .;
    mapperConfig = new DynamoDBMapperConfig.Builder().withTableNameOverride(TableNameOverride.withTableNameReplacement(tableName))
        .build();
    mapper = new DynamoDBMapper(client, mapperConfig);
like image 67
Chen Harel Avatar answered Nov 07 '22 11:11

Chen Harel