Saturday, August 21, 2021

How to use dynamic DynamoDB table name for query

In my current project, it requires to initialize the names of DynamoDB tables using environment variables during runtime. So far so good but 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 restrict me using the POJO in a dynamic manner.

Solution
Looking a bit closer at the DynamoMapper API, I found a class called DynamoDBMapperConfig. This class allows us to specify a so called TableNameOverride that overrides the table name defined in the DynamoDBTable annotation in Java class. You can supply a DynamoDBMapperConfig as a second parameter to several methods in the DynamoMapper API. 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 DynamoDBMapperConfig dynamoConfig = new DynamoDBMapperConfig(new DynamoDBMapperConfig.TableNameOverride(System.getenv("ID_TABLE")));

QueryResultPage queryResult = mapper.queryPage(IDRecord.class, queryExpression, dynamoConfig);

       
 

No comments:

Post a Comment