Problem:
Write Java Spring code to create DynamoDB Table, load data and do cleanup.
Solution Summary:
We will use Spring Boot project and AWS SDK.
Prerequisites:
This is a continuation to the lab: Setting Up Project and Environment For DynamoDB Java Spring Project.
Solution Steps:
The client of type AmazonDynamoDB returned by the context class can be autowired into a variable of same type within the data loader class and used to create the DynamoDB object.
final DynamoDB dynamoDB;
@Autowired
DefaultDataLoaderImpl(final AmazonDynamoDB client){
dynamoDB = new DynamoDB(client);
}
Table can be created using the AmazonDynamoDB client as follows:
if(dynamoDB.getTable("Employee").getDescription() != null) {
return;
}
System.out.println("Attempting to create table; please wait...");
Table table = dynamoDB.createTable(demoTableName,
Arrays.asList(
new KeySchemaElement("Name", KeyType.HASH), //Partition key
new KeySchemaElement("Designation", KeyType.RANGE)), //Sort key
Arrays.asList(
new AttributeDefinition("Name", ScalarAttributeType.S),
new AttributeDefinition("Designation", ScalarAttributeType.S)),
new ProvisionedThroughput(10L, 10L));
table.waitForActive();
System.out.println("Success. Table status: " + table.getDescription().getTableStatus());
Data is loaded from a json file EmployeeData.json as:
Table table = dynamoDB.getTable("Employee");
JsonParser parser = new JsonFactory()
.createParser(new File("EmployeeData.json"));
JsonNode rootNode = new ObjectMapper().readTree(parser);
Iterator<JsonNode> iter = rootNode.iterator();
ObjectNode currentNode;
while (iter.hasNext()) {
currentNode = (ObjectNode) iter.next();
String Name = currentNode.path("Name").asText();
String Designation = currentNode.path("Designation").asText();
try {
table.putItem(new Item()
.withPrimaryKey("Name", Name, "Designation", Designation));
System.out.println("PutItem succeeded: " + Name + " " + Designation);
} catch (Exception e) {
System.err.println("Unable to add employee: " + Name + " " + Designation);
System.err.println(e.getMessage());
break;
}
}
parser.close();
The data file EmployeeData.json has following contents:
[
{
"Name" : "Test0",
"Designation" : "CEO"
},
{
"Name" : "Test1",
"Designation" : "Software Engineer"
},
{
"Name" : "Test2",
"Designation" : "Admin"
},
{
"Name" : "Test3",
"Designation" : "HR"
},
{
"Name" : "Test4",
"Designation" : "Senior Software Engineer"
},
{
"Name" : "Test5",
"Designation" : "Lead"
}
]
Finally, there should be a method for clean up that will delete the table:
final Table table = dynamoDB.getTable(demoTableName);
System.out.println("Attempting to delete table; please wait...");
table.delete();
table.waitForDelete();
System.out.println("Success.");
Recent comments