Wednesday, July 27, 2022

Using dynamic table name when saving item to DynamDB Table

If you are using Java DynamoDBMapper API, it requires the annotation @DynamoDBTable on the POJO. This is a compile-time annotation and requires a table name parameter. How to change/pass this table name in runtime?

Solution
Looking a bit closer at the DynamoMapper API, I found a class called DynamoDBMapperConfig. This class has a builder method which allows us to specify a so called TableNameOverride that overrides the table name defined in the DynamoDBTable annotation in Java class. For example if you want to override the table name defined in the following class;
       

    @DynamoDBTable(tableName = "temp_name")
    public static class IDRecord {
        private String id;
        private String StartDate;
        private String EndDate;

        @DynamoDBHashKey(attributeName = "ID")
        public String geID() {
            return id;
        }

        public void setID(String id) {
            this.id = id;
        }

        @DynamoDBAttribute(attributeName = "StartDate")
        public String getStartDate() {
            return StartDate;
        }

        public void setStartDate(String StartDate) {
            this.StartDate = StartDate;
        }

        @DynamoDBAttribute(attributeName = "EndDate")
        public String getEndDate() {
            return EndDate;
        }

        public void setEndDate(String EndDate) {
            this.EndDate = EndDate;
        }

        @Override
        public String toString() {
            return "IDRecord [ID=" + id + ", StartDate=" + StartDate  + ", EndDate=" + EndDate+ "]";
        }

    }
  

       
 
when querying the table, do the following. This will ignore the table name defined by the @DynamoDBTable annotation in IDRecord class and instead use the tableName that we read from environment variable.
       

private static AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().withRegion("ap-southeast-2").build();
	
private static DynamoDBMapper dynamoDBMapper = new DynamoDBMapper(client);
    
DynamoDBMapperConfig mapperConfig = DynamoDBMapperConfig.builder().withTableNameOverride(new TableNameOverride(tableName)).build();
                
dynamoDBMapper.save(iDRecord, mapperConfig);

       
       
Note: In previous version, it had DynamoDBMapperConfig(DynamoDBMapperConfig.TableNameOverride tableNameOverride) which is now Deprecated