Problem:
DynamoDB Java APIs TableUtils class contains utility methods for working with DynamoDB tables. Experiment with it.
Solution Summary:
We will rewrite the table creation using createTableIfNotExists method so that we don’t have to worry about if the table is already present or not.
Prerequisites:
This is in continuation to the lab: Create Table, Load Data And Write Cleanup Code in Java Spring For DynamoDB
You don’t have to create DynamoDB object from the client object AmazonDynamoDB. However, you will need to retain it in current code as it is being used for loading data.
Solution Steps:
Code:
final AmazonDynamoDB amazonDynamoDB;
final DynamoDB dynamoDB;
…
@Autowired
DefaultDataLoaderImpl(AmazonDynamoDB amazonDynamoDB){
dynamoDB = new DynamoDB(amazonDynamoDB);
this.amazonDynamoDB = amazonDynamoDB;
}
Table Creation Code
public void createTable() throws InterruptedException {
CreateTableRequest createTableRequest = new CreateTableRequest(
Arrays.asList(
new AttributeDefinition("Name", ScalarAttributeType.S),
new AttributeDefinition("Designation", ScalarAttributeType.S)),
demoTableName,
Arrays.asList(
new KeySchemaElement("Name", KeyType.HASH), //Partition key
new KeySchemaElement("Designation", KeyType.RANGE)), //Sort key
new ProvisionedThroughput(10L, 10L));
System.out.println("Attempting to create table; please wait...");
TableUtils.createTableIfNotExists(amazonDynamoDB, createTableRequest);
try {
TableUtils.waitUntilActive(amazonDynamoDB, demoTableName);
} catch (AmazonClientException e) {
System.out.println("Failed.");
e.printStackTrace();
}
}
Other methods
TableUtils class has few other useful methods too such as:
- deleteTableIfExists(AmazonDynamoDB dynamo, DeleteTableRequest deleteTableRequest)
- waitUntilActive(AmazonDynamoDB dynamo, String tableName)
- waitUntilActive(AmazonDynamoDB dynamo, String tableName, int timeout, int interval)
- waitUntilExists(AmazonDynamoDB dynamo, String tableName)
- waitUntilExists(AmazonDynamoDB dynamo, String tableName, int timeout, int interval)
Recent comments