How to create table in dynamoDB using Java – DynamoDB Tutorial

4 weeks ago Lalit Bhagtani 0

In this tutorial, we will learn about how to create a new table in dynamoDB using java language.

DynamoDB

Amazon DynamoDB is a fully managed NoSQL database services offered by Amazon as part of its Amazon Web Service (AWS) portfolio. It provides fast and predictable performance with seamless scalability. DynamoDB is a key-value datastore, where each item (row) in a table is a key-value pair. The primary key is the only required attribute for an item and uniquely identifies each item. DynamoDB is schema-less, which means that each item in a table can have any number of attributes and the types of attributes can vary from item to item.

Project Setup

Create a simple maven project in your favorite IDE and add below mentioned dependency in your pom.xml file.

<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-java-sdk</artifactId>
  <version>1.11.524</version>
</dependency>

For latest version of aws library, check this page.

Table Schema

In this example, we will create a JOB table, which will store the information about the job posted by the company on the job portal. Schema of this table is as follows:-

  1. CountryName ( Partition Key ) :- It represents name of the country for which job is posted. It is stored as String data type ( ScalarAttributeType S ).
  2. JobId (Sort Key) :- It represents unique id of the posted job. It is of Number datatype ( ScalarAttributeType N ).
  3. CompanyName :- It represents name of the company by which job is posted. It is of String datatype ( ScalarAttributeType S ).
  4. JobTitle :- As the name suggest, it represents tile of the job. It is of String datatype ( ScalarAttributeType S ).
  5. JobDescription :- It represents details job description. It is of String datatype ( ScalarAttributeType S ).

JobTable

DynamoDB Connection

Create an object of AmazonDynamoDB ( com.amazonaws.services.dynamodbv2.AmazonDynamoDB ) class for sending a client request to dynamoDB. To get instance of this class, we will use AmazonDynamoDBClientBuilder builder class. It requires three important parameters :- 

  1. Region :- It is a region where dynamoDB table will be stored.
  2. ACCESS_KEY :- It is a access key for using dynamoDB. You can generate this key, using aws management console.
  3. SECRET_KEY :- It is a secret key of above mentioned access key.

Here is a code example :-

AmazonDynamoDB dynamoDB = AmazonDynamoDBClientBuilder.standard()
				.withRegion(Regions.AP_SOUTH_1)
				.withCredentials(new AWSStaticCredentialsProvider
                                                    (new BasicAWSCredentials("ACCESS_KEY","SECRET_KEY")))
				.build();

Create Table

Steps to create and send CreateTableRequest to dynamoDB are as follows:-

  1. Instantiate CreateTableRequest object, this object will be used to send the client request to dynamoDB.
  2. Set name of the table which we like to create. In our case JOB.
  3. Create a list of AttributeDefinition objects, It will define attribute names and their datatypes.
  4. Create a list of KeySchema objects, It will define partition key and sort key of the table.
  5. Set Provisioned Throughput of the table.
  6. Invoke the createTable method on AmazonDynamoDB object by passing CreateTableRequest object as an argument.

Example

import java.util.Arrays;
import java.util.List;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.CreateTableResult;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;

public class CreateTable {
	
	public static void main(String[] args) {
		
		/* Create DynamoDB Client Object */
		AmazonDynamoDB dynamoDB = AmazonDynamoDBClientBuilder
				.standard()
				.withRegion(Regions.AP_SOUTH_1)
				.withCredentials(new AWSStaticCredentialsProvider(
                                                     new BasicAWSCredentials("ACCESS_KEY","SECRET_KEY")))
				.build();
		
		/* Create an Object of CreateTableRequest */
		CreateTableRequest request = new CreateTableRequest();
		
		/* Setting Table Name */
		request.setTableName("JOB");
		
		/* Create & Set a list of AttributeDefinition */
		List<AttributeDefinition> attributeDefinitions = Arrays.asList(
				new AttributeDefinition[] { 
                                   new AttributeDefinition("CountryName", ScalarAttributeType.S),
                                   new AttributeDefinition("JobId", ScalarAttributeType.N) });
		request.setAttributeDefinitions(attributeDefinitions);
		
		/* Create & Set a list of KeySchemaElement */
		List<KeySchemaElement> keySchema = Arrays.asList(
				new KeySchemaElement[] { 
                                   new KeySchemaElement("CountryName", KeyType.HASH),
                                   new KeySchemaElement("JobId", KeyType.RANGE)});
		request.setKeySchema(keySchema);
		
		/* Setting Provisioned Throughput */
		request.setProvisionedThroughput(new ProvisionedThroughput(new Long(1), new Long(1)));
		
        try {
        	/* Send Create Table Request */
            CreateTableResult result = dynamoDB.createTable(request);
            
            System.out.println("Status : " +  result.getSdkHttpMetadata().getHttpStatusCode());
            
            System.out.println("Table Name : " +  result.getTableDescription().getTableName());
            
            /* Creating and Sending request using Fluent API - USER Table */
            CreateTableResult resultFluent = dynamoDB.createTable((new CreateTableRequest())
                    .withTableName("USER")
                    .withAttributeDefinitions(new AttributeDefinition("Id", ScalarAttributeType.N))
                    .withKeySchema(new KeySchemaElement("Id", KeyType.HASH))
                    .withProvisionedThroughput(new ProvisionedThroughput(new Long(1), new Long(1))));
            
            System.out.println("Status : " +  resultFluent.getSdkHttpMetadata().getHttpStatusCode());
            
            System.out.println("Table Name : " +  resultFluent.getTableDescription().getTableName());
            
        } catch (AmazonServiceException e) {
        	
            System.out.println(e.getErrorMessage());
            
        }
	}
	
}

References :-

  1. CreateTableRequest Java Docs
  2. CreateTableResult Java Docs

That’s all for how to create a new table in dynamoDB using java language. If you liked it, please share your thoughts in comments section and share it with others too.