derjust / spring-data-dynamodb

This module deals with enhanced support for a data access layer built on AWS DynamoDB.
https://derjust.github.io/spring-data-dynamodb/
Apache License 2.0
403 stars 141 forks source link

How can I have dynamodb table name dynamically based on my env? #297

Open manoj-ahi opened 2 years ago

manoj-ahi commented 2 years ago

Expected Behavior

I have my dev and stage env in one AWS region and I am using the suffix _dev and _stage to tables. Is there any way to add this suffix in runtime to @DynamoDBTable()?

Actual Behavior

I tried to override the value using TableNameResolver but the override method is not getting called. also, I tried with Spring expression to evaluate the expression but that is also not working.

Would appreciate any help. Thanks

ShubamVirdi commented 1 year ago

Hi You can achieve this by making a table name resolver


@Component
public class TableNameResolver extends DynamoDBMapperConfig.DefaultTableNameResolver {

    private String env;

    public TableNameResolver() {
    }

    public TableNameResolver(String envProfile) {
        this.env = envProfile;
    }

    @Override
    public String getTableName(Class<?> clazz, DynamoDBMapperConfig config) {
        String stageName = env;
        String rawTableName = super.getTableName(clazz, config);
        return String.join("_", rawTableName, stageName);
    }
}

in the class where you are creating dynamo db bean just pass env value (the env value can be saved at application yml for respective environments)

    @Value("${env}")
    private String env;

and create a dbmapper like this


    @Bean
    @Primary
    public DynamoDBMapper dynamoDBMapper(AmazonDynamoDB amazonDynamoDB) {

        return new DynamoDBMapper(amazonDynamoDB, new DynamoDBMapperConfig.Builder().withTableNameResolver(new TableNameResolver(env)).build());
    }

and now for table entities just provide the base name for the table and it will automatically append the env at the end of the table name.