3

I am trying to use Transactional writes for DynamoDB in Kotlin.

Use case : I want to write two different objects to two different tables in the same transaction. For example : write AClass to Table 1 and write BClass to Table 2.

This would've been straightforward if the names for Table1 and Table2 were same for every scenario.

However, I'm using serverless framework and depending on the stage which has been specified,

Table1 can be : local-Table1 / dev-Table1 / production-Table1.

Same for Table2

However, in my class decalaration of AClass, if I try to annotate AClass by @DynamoDBTable(tableName = "$stage-Table1"), I get the error An annotation argument must be a compile-time constant.

This means table name needs to be provided separately in the flow. To overcome this in usual write/get scenarios, I was using the following setting :

private val dynamoDBMapperConfig = DynamoDBMapperConfig.Builder()
        .withTableNameOverride(DynamoDBMapperConfig.TableNameOverride.withTableNameReplacement(tableName))
        .build()

mapper.save(t, dynamoDBMapperConfig)

As per the documentation, I will have to do the following :

TransactionWriteRequest transactionWriteRequest = new TransactionWriteRequest()
transactionWriteRequest.addPut(aClassObject)
transactionWriteRequest.addPut(bClassObject)
mapper.transactionWrite(transactionWriteRequest)

If objects of AClass and BClass were to be written in the same table, I could have again used a custom DynamoDBMapperConfig. However, both objects need to be written in two different tables and since table names need to be resolved during run-time, I can't give them as part of Class annotations.

How do I resolve this? ( I want to use object mapper )

Kancha
  • 409
  • 1
  • 3
  • 11

1 Answers1

0

I am using custom DynamoDB mapper to change the table name at runtime, since Table name is different in each environment.

Table:

@DynamoDBTable(tableName="dummy-table-Name")
public class DynamoTable

Custom mapper for dynamic table name:

DynamoDBMapperConfig.TableNameOverride tableNameOverriderride = new DynamoDBMapperConfig.TableNameOverride("DYNAMIC_TABLE_NAME");
DynamoDBMapperConfig config =new DynamoDBMapperConfig(tableNameOverriderride);
DynamoDBMapper mapper =new DynamoDBMapper(client, config);

Perform CRUD operation using above mapper:

DynamoTable dynamoTable = mapper.load(DynamoTable.class, id);

mapper.save(dynamoTable);
amitkumar12788
  • 797
  • 3
  • 10
  • 14