Page tree
Skip to end of metadata
Go to start of metadata

CAST supports DynamoDB via its NoSQL for Java extension. This document details about the support provided for Java source code.

Supported Client Libraries

Supported Operations

OperationsMethods Supported AWS SDK JAVA v1Methods Supported in v1 DDB MapperMethods Supported in AWS SDK JAVA v2Methods Supported in v2 EnhancedRemarks
Insert
  • putItem
  • putItemAsync
  • save
  • batchSave
  • putItem
  • putItem
batchWriteItems, transactWriteItems may result in useInsertLink, useUpdateLink or useDeleteLink depnding on the usage.
Update
  • updateTable
  • updateTableAsnc
  • updateItem
  • updaeItemAsync

  • updateTable
  • updateItem
  • upadateItem
Select
  • query
  • scan
  • scanAsync
  • describeTable
  • describeTableAsync
  • getItem
  • getItemAsync
  • load
  • query
  • count
  • scan
  • scanPage
  • queryPage
  • parallelScan
  • getTableModel
  • batchLoad
  • transasctionLoad
  • query
  • scan
  • describeTable
  • getItem
  • getItem
  • query
  • scan
  • readBatches
  • batchGetItem
  • transactGetItems
Delete
  • deleteTable
  • deleteItem
  • deleteTableAsync
  • deletItemAsync
  • delete
  • batchDelete
  • deleteTable
  • deleteItem
  • deleteItem

Objects

IconDescription

Java AWS DynamoDB Client

Java AWS DynamoDB Table

Java AWS Unknown DynamoDB Client

Java AWS Unknown DynamoDB Table

Links are created for transaction and function point needs:

Link typeSource and destination of linkMethods Supported in AWS SDK Java v1Methods Supported in AWS SDK Java v1 DynamoDB MapperMethods Supported in AWS SDK Java v2Methods Supported in v2 EnhancedRemarks
belongsTo

From Java AWS DynamoDB Table object to Java AWS DynamoDB Client object






useLinkBetween the caller Java Method objects and Java AWS DynamoDB table object
  • createTable
  • createTableAsync

  • createTable


useInsertLink
  • putItem
  • putItemAsync
  • save
  • batchSave
  • putItem
  • putItem



batchWriteItems, transactWriteItems may result in useInsertLink, useUpdateLink or useDeleteLink depnding on the usage.
useUpdateLink
  • updateTable
  • updateItem
  • updateTableAsync
  • updateItemAsync

  • updateTable
  • updateItem
  • upadateItem

useSelectLink

  • query
  • queryAsync
  • describeTable
  • describeTableAsync
  • getItem
  • getItemAsync
  • batchGetItem
  • batchGetItemAsync
  • transactGetItems
  • transactGetItemsAsync
  • load
  • query
  • count
  • scan
  • scanPage
  • queryPage
  • parallelScan
  • getTableModel
  • batchLoad
  • transasctionLoad
  • describeTable
  • getItem
  • query
  • scan
  • getItem
  • query
  • scan
  • readBatches
  • batchGetItem
  • transactGetItems
useDeleteLink
  • DeleteTable
  • DeleteItem
  • delete
  • batchDelete
  • deleteTable
  • deleteItem
  • deleteItem

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 main(String[] args)
    {
        final String USAGE = "\n" +
            "Usage:\n" +
            "    DeleteTable <table>\n\n" +
            "Where:\n" +
            "    table - the table to delete.\n\n" +
            "Example:\n" +
            "    DeleteTable Greetings\n\n" +
            "**Warning** This program will actually delete the table\n" +
            "            that you specify!\n";

        if (args.length < 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String table_name = "CustomerTable";

        System.out.format("Deleting table %s...\n", table_name);

        final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient();

        try {
            ddb.deleteTable(table_name);
        } 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);
}

 DeleteOperation
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!");
    }

 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);
        }

}

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
  • Better resolution for tables 

Limitations

  • DynamoDB client is created as unknown.

Future Scope

  • To provide support for batch transactions in AWS SDK Java v2 library (support for batch transactions in Enhanced client exists.)
  • No labels