javaamazon-web-servicesamazon-dynamodbaws-java-sdk-2.x

AWS Java SDK v2.0: How to handle providing indexNames at runtime rather than using annotation


I have a project using DynamoDB which I'm upgrading to Java SDK v2.0

Using the new enhanced client and type mapping.

I have an index name which I need to pass to @DynamoDbSecondaryPartitionKey, however this name is stored in our application configuration (application.properties)

Usually I grab this using a config lookup class, which needs to happen at runtime using an injected dependency.

However the annotation param indexNames is passed statically.

Is there an alternative to the annotation @DynamoDbSecondaryPartitionKey which I can invoke at runtime, fetch the name from config, and set the index name?


Solution

  • You can write your own query completely ignoring any annotation, where the parameter are provided from the code.

    This is an example from my own project, where there's a key userId and secondaryI index createdTimestamp

    QueryRequest query = this.createListItemQueryRequest(userId, lastItem, size);
    QueryResponse queryResponse = this.getDynamoDbclient().query(query);  
    ...
    
    
    
      private QueryRequest createListItemQueryRequest(String userId, String lastItem, int size) {
    
            Map<String, AttributeValue> expressionValueMap = new HashMap<>();
            expressionValueMap.put(":userId", AttributeValue.fromS(userId));
            expressionValueMap.put(":lastItem", AttributeValue.fromN(
                    lastItem != null ? lastItem : this.longFormatter.format(System.currentTimeMillis())));
    
            QueryRequest query =  QueryRequest.builder()
                    .tableName(this.tableName)
                    .projectionExpression(ATT_TO_GET_LIST)
                    .keyConditionExpression("userId = :userId and createdTimestamp < :lastItem")
                    .expressionAttributeValues(expressionValueMap)
                    .indexName(this.userIndexName)
                    .scanIndexForward(false)
                    .limit(size)
                    .build();
    
            return query;
        }