0
0
DynamodbHow-ToBeginner · 4 min read

How to Use DynamoDB with Java: Simple Guide and Example

To use DynamoDB with Java, include the AWS SDK for Java in your project, create a DynamoDbClient instance, and use it to perform operations like putting and getting items. You write Java code that calls DynamoDB APIs through this client to interact with your database tables.
📐

Syntax

Using DynamoDB with Java involves these main parts:

  • Import AWS SDK classes: To access DynamoDB features.
  • Create a DynamoDbClient: This client connects your Java app to DynamoDB.
  • Build requests: For example, PutItemRequest to add data or GetItemRequest to read data.
  • Call client methods: Like putItem() or getItem() to execute operations.
java
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import java.util.Map;

// Create DynamoDbClient
DynamoDbClient ddb = DynamoDbClient.create();

// Prepare a PutItemRequest
PutItemRequest putReq = PutItemRequest.builder()
    .tableName("TableName")
    .item(Map.of("Key", AttributeValue.builder().s("Value").build()))
    .build();

// Put item
ddb.putItem(putReq);

// Prepare a GetItemRequest
GetItemRequest getReq = GetItemRequest.builder()
    .tableName("TableName")
    .key(Map.of("Key", AttributeValue.builder().s("Value").build()))
    .build();

// Get item
ddb.getItem(getReq);
💻

Example

This example shows how to put an item into a DynamoDB table and then get it back using Java.

java
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;

import java.util.HashMap;
import java.util.Map;

public class DynamoDBExample {
    public static void main(String[] args) {
        String tableName = "Movies";
        String movieId = "123";

        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        try {
            // Create item to put
            Map<String, AttributeValue> itemValues = new HashMap<>();
            itemValues.put("Id", AttributeValue.builder().s(movieId).build());
            itemValues.put("Title", AttributeValue.builder().s("Inception").build());
            itemValues.put("Year", AttributeValue.builder().n("2010").build());

            PutItemRequest putReq = PutItemRequest.builder()
                    .tableName(tableName)
                    .item(itemValues)
                    .build();

            ddb.putItem(putReq);
            System.out.println("Item added to table.");

            // Prepare key to get
            Map<String, AttributeValue> keyToGet = new HashMap<>();
            keyToGet.put("Id", AttributeValue.builder().s(movieId).build());

            GetItemRequest getReq = GetItemRequest.builder()
                    .tableName(tableName)
                    .key(keyToGet)
                    .build();

            Map<String, AttributeValue> returnedItem = ddb.getItem(getReq).item();

            if (returnedItem != null) {
                System.out.println("Retrieved item:");
                returnedItem.forEach((k, v) -> System.out.println(k + ": " + v.toString()));
            } else {
                System.out.println("No item found with the key.");
            }

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
        } finally {
            ddb.close();
        }
    }
}
Output
Item added to table. Retrieved item: Id: S=123 Title: S=Inception Year: N=2010
⚠️

Common Pitfalls

Some common mistakes when using DynamoDB with Java include:

  • Not setting the AWS region in the DynamoDbClient, causing connection errors.
  • Forgetting to close the DynamoDbClient, which can lead to resource leaks.
  • Incorrectly formatting the item attributes, such as missing AttributeValue wrappers.
  • Using wrong table names or keys that don't exist, resulting in empty results.
java
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;

/* Wrong: Missing region setting */
DynamoDbClient ddbWrong = DynamoDbClient.create(); // May fail if region not set

/* Right: Set region explicitly */
DynamoDbClient ddbRight = DynamoDbClient.builder()
    .region(Region.US_EAST_1)
    .build();
📊

Quick Reference

Here is a quick summary of key DynamoDB Java SDK classes and methods:

ConceptDescription
DynamoDbClientMain client to connect and perform operations on DynamoDB.
PutItemRequestRequest object to add an item to a table.
GetItemRequestRequest object to retrieve an item by key.
AttributeValueWrapper class for attribute data types (String, Number, etc).
RegionAWS region where your DynamoDB table is located.

Key Takeaways

Always create a DynamoDbClient with the correct AWS region before calling DynamoDB.
Use AttributeValue wrappers to format item attributes properly in requests.
Close the DynamoDbClient after use to free resources.
Check your table name and key attributes carefully to avoid empty results.
Use PutItemRequest and GetItemRequest to add and retrieve items respectively.