- Created by user-1a1b1, last modified by Shared Doc User on Mar 31, 2023
CAST supports DynamoDB via its NoSQL for Java extension. This document details about the support provided for Java source code.
Supported Client Libraries
Library | Supported? |
---|---|
AWS SDK for Java API - v1 | |
AWS SDK for Java API - v2 |
Supported Operations
Operations | Methods Supported |
---|---|
Insert | AWS SDK JAVA v1
DDB Mapper v1
AWS SDK JAVA v2
Enhanced v2
|
Update | AWS SDK JAVA v1
DDB Mapper v1
AWS SDK JAVA v2
Enhanced v2
|
Select | AWS SDK JAVA v1
DDB Mapper v1
AWS SDK JAVA v2
Enhanced v2
|
Delete | AWS SDK JAVA v1
DDB Mapper v1
AWS SDK JAVA v2
Enhanced v2
|
Note : batchWriteItems, transactWriteItems may result in useInsertLink, useUpdateLink or useDeleteLink depnding on the usage.
Objects
Icon | Description |
---|---|
Java AWS DynamoDB Client | |
Java AWS DynamoDB Table | |
Java AWS Unknown DynamoDB Client | |
Java AWS Unknown DynamoDB Table |
Links
Links are created for transaction and function point needs:
Link type | Source and destination of link | Methods Supported in AWS SDK Java v1 | Methods Supported in AWS SDK Java v1 DynamoDB Mapper | Methods Supported in AWS SDK Java v2 | Methods Supported in v2 Enhanced | Remarks |
---|---|---|---|---|---|---|
belongsTo | From Java AWS DynamoDB Table object to Java AWS DynamoDB Client object | |||||
useLink | Between the caller Java Method objects and Java AWS DynamoDB table object |
|
| |||
useInsertLink |
|
|
|
| batchWriteItems, transactWriteItems may result in useInsertLink, useUpdateLink or useDeleteLink depnding on the usage. | |
useUpdateLink |
|
|
| |||
useSelectLink |
|
|
|
| ||
useDeleteLink |
|
|
|
|
What results can you expect?
Once the analysis/snapshot generation is completed, you can view the results in the normal manner (for example via CAST Enlighten). Some examples are shown below.
AWS SDK JAVA v1
AWS SDK JAVA v1
DynamoDB Client Configuration
public static void main(String[] args) { final String USAGE = "\n" + "Usage:\n" + " CreateTable <table>\n\n" + "Where:\n" + " table - the table to create.\n\n" + "Example:\n" + " CreateTable HelloTable\n"; if (args.length < 1) { System.out.println(USAGE); System.exit(1); } /* Read the name from command args */ String table_name = "Customer Table"; System.out.format( "Creating table \"%s\" with a simple primary key: \"Name\".\n", table_name); CreateTableRequest request = new CreateTableRequest() .withAttributeDefinitions(new AttributeDefinition( "Name", ScalarAttributeType.S)) .withKeySchema(new KeySchemaElement("Name", KeyType.HASH)) .withProvisionedThroughput(new ProvisionedThroughput( new Long(10), new Long(10))) .withTableName(table_name); final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient(); try { CreateTableResult result = ddb.createTable(request); System.out.println(result.getTableDescription().getTableName()); } catch (AmazonServiceException e) { System.err.println(e.getErrorMessage()); System.exit(1); } System.out.println("Done!"); }
Insert Operation
Insert Operation
public static void main(String args[]) throws InterruptedException { AmazonDynamoDB dynamoDBClient = AmazonDynamoDBClientBuilder .standard() .withRegion(Regions.US_EAST_2) .withCredentials(new DefaultAWSCredentialsProviderChain()) .build(); int maxItemCount = 100; for (Integer i = 1; i <= maxItemCount; i++) { System.out.println("Processing item " + i + " of " + maxItemCount); // Write a new item Map<String, AttributeValue> item = new HashMap<>(); item.put("Id", new AttributeValue().withN(i.toString())); item.put("Message", new AttributeValue().withS("New item!")); dynamoDBClient.putItem(tableName, item); } }
Delete Operation
public static void TestDeleteTable() { String table_name = "Products2"; DeleteTableRequest request = new DeleteTableRequest().withTableName(table_name); final AmazonDynamoDB ddb2 = AmazonDynamoDBClientBuilder.defaultClient(); try { ddb2.deleteTable(request); } catch (AmazonServiceException e) { System.err.println(e.getErrorMessage()); System.exit(1); } System.out.println("Done!"); }
Update Operation
public static void main(String args[]) throws InterruptedException { AmazonDynamoDB dynamoDBClient = AmazonDynamoDBClientBuilder .standard() .withRegion(Regions.US_EAST_2) .withCredentials(new DefaultAWSCredentialsProviderChain()) .build(); Map<String, AttributeValue> key = new HashMap<>(); key.put("Id", new AttributeValue().withN(i.toString())); Map<String, AttributeValueUpdate> attributeUpdates = new HashMap<>(); attributeUpdates.put("Message", new AttributeValueUpdate() .withAction(AttributeAction.PUT) .withValue(new AttributeValue() .withS("This item has changed"))); dynamoDBClient.updateItem(tableName, key, attributeUpdates);
Select Operation
public static void main(String args[]) throws InterruptedException { AmazonDynamoDB dynamoDBClient = AmazonDynamoDBClientBuilder .standard() .withRegion(Regions.US_EAST_2) .withCredentials(new DefaultAWSCredentialsProviderChain()) .build(); String tableName = "TestTableForStreams"; // Print the stream settings for the table DescribeTableResult describeTableResult = dynamoDBClient.describeTable(tableName); String streamArn = describeTableResult.getTable().getLatestStreamArn(); System.out.println("Current stream ARN for " + tableName + ": " + describeTableResult.getTable().getLatestStreamArn());
Batch Operations
Batch Operations
BatchWriteRequest
Map<String, AttributeValue> book_item1 = new HashMap<String, AttributeValue>(); WriteRequest req1= new WriteRequest().withDeleteRequest(new DeleteRequest(book_item1)); WriteRequest req2= new WriteRequest().withPutRequest(new PutRequest(book_item2)); List<WriteRequest> requests1=new ArrayList<WriteRequest>(); requests1.add(req1); requests1.add(req2); List<WriteRequest> requests2=new ArrayList<WriteRequest>(); requests2.add(new WriteRequest().withDeleteRequest(new DeleteRequest(book_item3))); Map<String, List<WriteRequest>> requestItems = new HashMap<String, List<WriteRequest>>() ; requestItems.put("table1",requests1); requestItems.put("table2",requests2); BatchWriteItemRequest batchWriteItemRequest1=new BatchWriteItemRequest().withRequestItems(requestItems); ddb1.batchWriteItem(batchWriteItemRequest1) ;
BatchGetItemRequest
KeysAndAttributes item1 = null; KeysAndAttributes item2 = null; Map<String, KeysAndAttributes> requestItems = new HashMap<String, KeysAndAttributes>(); requestItems.put("table1",item1); requestItems.put("table2",item2); BatchGetItemRequest batchGetItemRequest1 = new BatchGetItemRequest().withRequestItems(requestItems); ddb2.batchGetItem(batchGetItemRequest1) ;
TransactWriteItemsRequest
Put putItem1= new Put().withTableName("table1").withItem(book_item1); Delete deleteItem1= new Delete().withTableName("table1").withKey(book_item2); Update updateItem1=new Update().withTableName("table2").withKey(book_item3); TransactWriteItem transactItem1=new TransactWriteItem().withPut(putItem1); TransactWriteItem transactItem2=new TransactWriteItem().withDelete(deleteItem1); TransactWriteItem transactItem3=new TransactWriteItem().withUpdate(updateItem1); TransactWriteItemsRequest transactWriteItemsRequest= new TransactWriteItemsRequest().withTransactItems(transactItem1,transactItem2,transactItem3); ddb3.transactWriteItems(transactWriteItemsRequest);
TransactGetItemsRequest
Get getItem1= new Get().withTableName("table1").withKey(book_item1); Get getItem2=new Get().withTableName("table2").withKey(book_item2); TransactGetItem transactItem1=new TransactGetItem().withGet(getItem1); TransactGetItem transactItem2=new TransactGetItem().withGet(getItem2); TransactGetItemsRequest transactGetItemsRequest= new TransactGetItemsRequest().withTransactItems(transactItem1,transactItem2); ddb4.transactGetItems(transactGetItemsRequest);
AWS SDK JAVA v1 DynamoDB Mapper
DynamodB Mapper
Insert Operation
public void likeMysfit(String mysfitId) { Mysfit mysfitToUpdate = mapper.load(Mysfit.class, mysfitId); Integer likes = mysfitToUpdate.getLikes() + 1; mysfitToUpdate.setLikes(likes); mapper.save(mysfitToUpdate); }
Select Operation
public Mysfits queryMysfits(String filter, String value) { HashMap<String, AttributeValue> attribValue = new HashMap<String, AttributeValue>(); attribValue.put(":"+value, new AttributeValue().withS(value)); DynamoDBQueryExpression<Mysfit> queryExpression = new DynamoDBQueryExpression<Mysfit>() .withIndexName(filter+"Index") .withKeyConditionExpression(filter + "= :" + value) .withExpressionAttributeValues(attribValue) .withConsistentRead(false); List<Mysfit> mysfits = mapper.query(Mysfit.class, queryExpression); Mysfits allMysfits = new Mysfits(mysfits); return allMysfits; }
AWS SDK JAVA v2
AWS SDK Java v2
Insert Operation
public static void putItemInTable(DynamoDbClient ddb, String tableName, String key, String keyVal, String albumTitle, String albumTitleValue, String awards, String awardVal, String songTitle, String songTitleVal){ HashMap<String,AttributeValue> itemValues = new HashMap<String,AttributeValue>(); // Add all content to the table itemValues.put(key, AttributeValue.builder().s(keyVal).build()); itemValues.put(songTitle, AttributeValue.builder().s(songTitleVal).build()); itemValues.put(albumTitle, AttributeValue.builder().s(albumTitleValue).build()); itemValues.put(awards, AttributeValue.builder().s(awardVal).build()); PutItemRequest request = PutItemRequest.builder() .tableName(tableName) .item(itemValues) .build(); try { ddb.putItem(request); System.out.println(tableName +" was successfully updated"); } catch (ResourceNotFoundException e) { System.err.format("Error: The Amazon DynamoDB table \"%s\" can't be found.\n", tableName); System.err.println("Be sure that it exists and that you've typed its name correctly!"); System.exit(1); }
Delete Operation
public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { DeleteTableRequest request = DeleteTableRequest.builder() .tableName(tableName) .build(); try { ddb.deleteTable(request); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println(tableName +" was successfully deleted!"); }
Update Operation
public static void updateDynamoDBTable(DynamoDbClient ddb, String tableName, Long readCapacity, Long writeCapacity) { System.out.format( "Updating %s with new provisioned throughput values\n", tableName); System.out.format("Read capacity : %d\n", readCapacity); System.out.format("Write capacity : %d\n", writeCapacity); ProvisionedThroughput tableThroughput = ProvisionedThroughput.builder() .readCapacityUnits(readCapacity) .writeCapacityUnits(writeCapacity) .build(); UpdateTableRequest request = UpdateTableRequest.builder() .provisionedThroughput(tableThroughput) .tableName(tableName) .build(); try { ddb.updateTable(request); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println("Done!"); }
public static void updateDynamoDBTable(DynamoDbClient ddb, String tableName, Long readCapacity, Long writeCapacity) { System.out.format( "Updating %s with new provisioned throughput values\n", tableName); System.out.format("Read capacity : %d\n", readCapacity); System.out.format("Write capacity : %d\n", writeCapacity); ProvisionedThroughput tableThroughput = ProvisionedThroughput.builder() .readCapacityUnits(readCapacity) .writeCapacityUnits(writeCapacity) .build(); UpdateTableRequest request = UpdateTableRequest.builder() .provisionedThroughput(tableThroughput) .tableName(tableName) .build(); try { ddb.updateTable(request); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println("Done!"); }
Select Operation
public static int queryTable(DynamoDbClient ddb, String tableName, String partitionKeyName, String partitionKeyVal, String partitionAlias) { HashMap<String,String> attrNameAlias = new HashMap<String,String>(); attrNameAlias.put(partitionAlias, partitionKeyName); // Set up mapping of the partition name with the value HashMap<String, AttributeValue> attrValues = new HashMap<String,AttributeValue>(); attrValues.put(":"+partitionKeyName, AttributeValue.builder() .s(partitionKeyVal) .build()); QueryRequest queryReq = QueryRequest.builder() .tableName(tableName) .keyConditionExpression(partitionAlias + " = :" + partitionKeyName) .expressionAttributeNames(attrNameAlias) .expressionAttributeValues(attrValues) .build(); try { QueryResponse response = ddb.query(queryReq); return response.count(); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } return -1; }
AWS JAVA SDK v2 - Enhanced
AWS SDK JAVA v2 Enhanced
Insert Operation
public static void putRecord(DynamoDbEnhancedClient enhancedClient) { try { DynamoDbTable<Customer> custTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class)); // Create an Instant LocalDate localDate = LocalDate.parse("2021-08-16"); LocalDateTime localDateTime = localDate.atStartOfDay(); Instant instant = localDateTime.toInstant(ZoneOffset.UTC); // Populate the Table Customer custRecord = new Customer(); custRecord.setCustName("Susan red"); custRecord.setId("id66"); custRecord.setEmail("abc@xyz.com"); custRecord.setRegistrationDate(instant) ; // Put the customer data into a DynamoDB table custTable.putItem(custRecord); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println("done"); }
Update Operation
public static String modifyItem(DynamoDbEnhancedClient enhancedClient, String keyVal, String email) { try { //Create a DynamoDbTable object DynamoDbTable<Customer> mappedTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class)); //Create a KEY object Key key = Key.builder() .partitionValue(keyVal) .build(); // Get the item by using the key and update the email value. Customer customerRec = mappedTable.getItem(r->r.key(key)); customerRec.setEmail(email); mappedTable.updateItem(customerRec); return customerRec.getEmail(); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } return ""; }
Select Operation
public static String getItem(DynamoDbEnhancedClient enhancedClient) { try { //Create a DynamoDbTable object DynamoDbTable<Customer> mappedTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class)); //Create a KEY object Key key = Key.builder() .partitionValue("id120") .build(); // Get the item by using the key Customer result = mappedTable.getItem(r->r.key(key)); return "The email valie is "+result.getEmail(); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } }
Region_property
Property
public static void main(String[] args) { final String usage = "\n" + "Usage:\n" + " <tableName>\n\n" + "Where:\n" + " tableName - The Amazon DynamoDB table to get information about (for example, Music3).\n\n" ; if (args.length != 1) { System.out.println(usage); System.exit(1); } String tableName = "Test"; System.out.format("Getting description for %s\n\n", tableName); Regions region = Regions.US_WEST_2; AmazonDynamoDB ddb1 = AmazonDynamoDBClientBuilder.standard() .withRegion(region) .build(); CreateTableRequest request = new CreateTableRequest() .withAttributeDefinitions(new AttributeDefinition("Name", ScalarAttributeType.S)) .withKeySchema(new KeySchemaElement("Name", KeyType.HASH)) .withProvisionedThroughput(new ProvisionedThroughput(new Long(10), new Long(10))).withTableName(Table1); TestDescribeTable(ddb1,tableName); ddb1.close(); System.out.println("Done!"); } public static void TestDescribeTable(AmazonDynamoDB ddb1,String tableName) { System.out.format("Getting description for %s\n\n", table_name); try { DescribeTableResult table_info1 = ddb1.describeTable(tableName); // ddb4.describeTable(table_name).getTable(); TableDescription table_info = table_info1.getTable(); if (table_info != null) { System.out.format("Table name : %s\n", table_info.getTableName()); System.out.format("Table ARN : %s\n", table_info.getTableArn()); System.out.format("Status : %s\n", table_info.getTableStatus()); System.out.format("Item count : %d\n", table_info.getItemCount().longValue()); System.out.format("Size (bytes): %d\n", table_info.getTableSizeBytes().longValue()); ProvisionedThroughputDescription throughput_info = table_info.getProvisionedThroughput(); System.out.println("Throughput"); System.out.format(" Read Capacity : %d\n", throughput_info.getReadCapacityUnits().longValue()); System.out.format(" Write Capacity: %d\n", throughput_info.getWriteCapacityUnits().longValue()); List<AttributeDefinition> attributes = table_info.getAttributeDefinitions(); System.out.println("Attributes"); for (AttributeDefinition a : attributes) { System.out.format(" %s (%s)\n", a.getAttributeName(), a.getAttributeType()); } } } catch (AmazonServiceException e) { System.err.println(e.getErrorMessage()); System.exit(1); } System.out.println("\nDone!"); } }
Evolution
- Support for the following have been implemented
- AWS SDK Java v1 - DynamoDB Mapper APIs
- sync version - asynchronous does not exist in DynamoDB Mapper
- AWS SDK Java v2
- Both synchronous and asynchronous version
- AWS SDK Java v2 - Enhanced client APIs
- Both synchronous and asynchronous versions
- AWS SDK Java v1 - DynamoDB Mapper APIs
- Better resolution for tables
- No labels