Back to Database & SQL

aws-sdk-java-v2-dynamodb

AWSDynamoDBJavaSDK v2NoSQLCloudBackendData Management
282📄 MIT🕒 2026-06-15Source ↗

Install this skill

npx skills add giuseppe-trisciuoglio/developer-kit

Works across Claude Code, Cursor, Codex, Copilot & Antigravity

The aws-sdk-java-v2-dynamodb skill provides a programmatic interface for interacting with Amazon DynamoDB using Java 2.x libraries. It centers on the Enhanced Client, which streamlines database interactions by mapping POJOs directly to DynamoDB tables through annotations like @DynamoDbBean. This tool manages the lifecycle of NoSQL data, including schema definitions, CRUD operations, transactional consistency, and batch processing. It abstracts the complexities of low-level AttributeValue types, allowing developers to manipulate table items as strongly-typed Java objects. The skill is specifically built for integration within JVM-based applications that require scalable, low-latency persistent storage, ensuring reliable communication with AWS database services via standardized synchronous client builders.

When to Use This Skill

  • Building microservices on Spring Boot requiring NoSQL persistence
  • Managing user sessions or high-frequency event logs in DynamoDB
  • Synchronizing multiple tables atomically using transactional requests
  • Implementing efficient bulk-data migration or backup tasks

How to Invoke This Skill

Example prompts that trigger this skill in Claude Code, Cursor, or Antigravity:

  • Map a Java object to a DynamoDB table
  • Implement transactional write in DynamoDB using Java
  • Perform a batch get operation with AWS SDK v2
  • Query a DynamoDB table using filter expressions in Java
  • Define partition and sort keys for a DynamoDbBean

Pro Tips

  • 💡Always prefer the DynamoDB Enhanced Client for type-safe operations, simplified POJO mapping, and reduced boilerplate code.
  • 💡Utilize batch write and get operations for multiple item interactions to minimize network overhead and significantly improve application throughput.
  • 💡Carefully design your primary key and secondary indexes to support common query patterns and avoid costly full table scans, especially for large datasets.

What this skill does

  • POJO-to-table mapping using DynamoDbBean annotations
  • Transactional read and write operations for atomic updates
  • Batch processing for bulk data retrieval or insertion
  • Type-safe CRUD operations via the Enhanced Client
  • Conditional querying and scanning with expression builders

When not to use it

  • Applications requiring complex relational joins or foreign key constraints
  • Situations where ACID compliance is needed across different non-AWS database engines
  • Small-scale projects where standard SQL databases offer lower latency and lower configuration overhead

Example workflow

  1. Configure the DynamoDbClient and instantiate the EnhancedClient
  2. Define a POJO with @DynamoDbBean, @DynamoDbPartitionKey, and @DynamoDbSortKey annotations
  3. Initialize a TableSchema to map the POJO to a specific table name
  4. Perform a putItem operation to insert a record into the database
  5. Use QueryConditional to retrieve specific items based on key indices
  6. Close or release client connections after operations complete

Prerequisites

  • AWS credentials configured via environment variables or profile
  • AWS SDK for Java v2 dependency in project build file
  • Existing DynamoDB table created in AWS account

Pitfalls & limitations

  • !Forgetting to register custom converters for complex object types
  • !Exceeding 25 items or 16MB limit in batch operations
  • !Mixing low-level and enhanced client logic without proper mapping
  • !Incorrectly configuring the partition key which can lead to hot partitions

FAQ

Why use the Enhanced Client instead of the low-level client?
The Enhanced Client reduces boilerplate code by automatically mapping Java objects to DynamoDB attributes, providing better type safety and cleaner maintenance.
Can I use this for non-annotated classes?
Yes, you can define the TableSchema manually without using annotations, though @DynamoDbBean is the standard approach for maintainable code.
Does this SDK support asynchronous operations?
The SDK provides both synchronous and asynchronous clients, though the Enhanced Client examples typically focus on synchronous request patterns.

How it compares

Unlike raw JSON manipulation or standard REST API calls, this SDK provides compile-time type checking and direct object mapping, which eliminates manual parsing errors and simplifies database logic.

Source & trust

282 stars📄 MIT🕒 Updated 2026-06-15
📄 Full skill instructions — original source: giuseppe-trisciuoglio/developer-kit
# AWS SDK for Java 2.x - Amazon DynamoDB

## When to Use

Use this skill when:
- Creating, updating, or deleting DynamoDB tables
- Performing CRUD operations on DynamoDB items
- Querying or scanning tables
- Working with Global Secondary Indexes (GSI) or Local Secondary Indexes (LSI)
- Implementing batch operations for efficiency
- Using DynamoDB transactions
- Integrating DynamoDB with Spring Boot applications
- Working with DynamoDB Enhanced Client for type-safe operations

## Dependencies

Add to pom.xml:
<!-- Low-level DynamoDB client -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>dynamodb</artifactId>
</dependency>

<!-- Enhanced client (recommended) -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>dynamodb-enhanced</artifactId>
</dependency>


## Client Setup

### Low-Level Client
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;

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


### Enhanced Client (Recommended)
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;

DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(dynamoDb)
.build();


## Entity Mapping

To define DynamoDB entities, use @DynamoDbBean annotation:

@DynamoDbBean
public class Customer {

@DynamoDbPartitionKey
private String customerId;

@DynamoDbAttribute("customer_name")
private String name;

private String email;

@DynamoDbSortKey
private String orderId;

// Getters and setters
}


For complex entity mapping with GSIs and custom converters, see [Entity Mapping Reference](references/entity-mapping.md).

## CRUD Operations

### Basic Operations
// Create or update item
DynamoDbTable<Customer> table = enhancedClient.table("Customers", TableSchema.fromBean(Customer.class));
table.putItem(customer);

// Get item
Customer result = table.getItem(Key.builder().partitionValue(customerId).build());

// Update item
return table.updateItem(customer);

// Delete item
table.deleteItem(Key.builder().partitionValue(customerId).build());


### Composite Key Operations
// Get item with composite key
Order order = table.getItem(Key.builder()
.partitionValue(customerId)
.sortValue(orderId)
.build());


## Query Operations

### Basic Query
import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional;

QueryConditional queryConditional = QueryConditional
.keyEqualTo(Key.builder()
.partitionValue(customerId)
.build());

List<Order> orders = table.query(queryConditional).items().stream()
.collect(Collectors.toList());


### Advanced Query with Filters
import software.amazon.awssdk.enhanced.dynamodb.Expression;

Expression filter = Expression.builder()
.expression("status = :pending")
.putExpressionValue(":pending", AttributeValue.builder().s("PENDING").build())
.build();

List<Order> pendingOrders = table.query(r -> r
.queryConditional(queryConditional)
.filterExpression(filter))
.items().stream()
.collect(Collectors.toList());


For detailed query patterns, see [Advanced Operations Reference](references/advanced-operations.md).

## Scan Operations

// Scan all items
List<Customer> allCustomers = table.scan().items().stream()
.collect(Collectors.toList());

// Scan with filter
Expression filter = Expression.builder()
.expression("points >= :minPoints")
.putExpressionValue(":minPoints", AttributeValue.builder().n("1000").build())
.build();

List<Customer> vipCustomers = table.scan(r -> r.filterExpression(filter))
.items().stream()
.collect(Collectors.toList());


## Batch Operations

### Batch Get
import software.amazon.awssdk.enhanced.dynamodb.model.*;

List<Key> keys = customerIds.stream()
.map(id -> Key.builder().partitionValue(id).build())
.collect(Collectors.toList());

ReadBatch.Builder<Customer> batchBuilder = ReadBatch.builder(Customer.class)
.mappedTableResource(table);

keys.forEach(batchBuilder::addGetItem);

BatchGetResultPageIterable result = enhancedClient.batchGetItem(r ->
r.addReadBatch(batchBuilder.build()));

List<Customer> customers = result.resultsForTable(table).stream()
.collect(Collectors.toList());


### Batch Write
WriteBatch.Builder<Customer> batchBuilder = WriteBatch.builder(Customer.class)
.mappedTableResource(table);

customers.forEach(batchBuilder::addPutItem);

enhancedClient.batchWriteItem(r -> r.addWriteBatch(batchBuilder.build()));


## Transactions

### Transactional Write
enhancedClient.transactWriteItems(r -> r
.addPutItem(customerTable, customer)
.addPutItem(orderTable, order));


### Transactional Read
TransactGetItemsEnhancedRequest request = TransactGetItemsEnhancedRequest.builder()
.addGetItem(customerTable, customerKey)
.addGetItem(orderTable, orderKey)
.build();

List<Document> results = enhancedClient.transactGetItems(request);


## Spring Boot Integration

### Configuration
@Configuration
public class DynamoDbConfiguration {

@Bean
public DynamoDbClient dynamoDbClient() {
return DynamoDbClient.builder()
.region(Region.US_EAST_1)
.build();
}

@Bean
public DynamoDbEnhancedClient dynamoDbEnhancedClient(DynamoDbClient dynamoDbClient) {
return DynamoDbEnhancedClient.builder()
.dynamoDbClient(dynamoDbClient)
.build();
}
}


### Repository Pattern
@Repository
public class CustomerRepository {

private final DynamoDbTable<Customer> customerTable;

public CustomerRepository(DynamoDbEnhancedClient enhancedClient) {
this.customerTable = enhancedClient.table("Customers", TableSchema.fromBean(Customer.class));
}

public void save(Customer customer) {
customerTable.putItem(customer);
}

public Optional<Customer> findById(String customerId) {
Key key = Key.builder().partitionValue(customerId).build();
return Optional.ofNullable(customerTable.getItem(key));
}
}


For comprehensive Spring Boot integration patterns, see [Spring Boot Integration Reference](references/spring-boot-integration.md).

## Testing

### Unit Testing with Mocks
@ExtendWith(MockitoExtension.class)
class CustomerServiceTest {

@Mock
private DynamoDbClient dynamoDbClient;

@Mock
private DynamoDbEnhancedClient enhancedClient;

@Mock
private DynamoDbTable<Customer> customerTable;

@InjectMocks
private CustomerService customerService;

@Test
void saveCustomer_ShouldReturnSavedCustomer() {
// Arrange
when(enhancedClient.table(anyString(), any(TableSchema.class)))
.thenReturn(customerTable);

Customer customer = new Customer("123", "John Doe", "[email protected]");

// Act
Customer result = customerService.saveCustomer(customer);

// Assert
assertNotNull(result);
verify(customerTable).putItem(customer);
}
}


### Integration Testing with LocalStack
@Testcontainers
@SpringBootTest
class DynamoDbIntegrationTest {

@Container
static LocalStackContainer localstack = new LocalStackContainer(
DockerImageName.parse("localstack/localstack:3.0"))
.withServices(LocalStackContainer.Service.DYNAMODB);

@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
registry.add("aws.endpoint",
() -> localstack.getEndpointOverride(LocalStackContainer.Service.DYNAMODB).toString());
}

@Autowired
private DynamoDbEnhancedClient enhancedClient;

@Test
void testCustomerCRUDOperations() {
// Test implementation
}
}


For detailed testing strategies, see [Testing Strategies](references/testing-strategies.md).

## Best Practices

1. **Use Enhanced Client**: Provides type-safe operations with less boilerplate
2. **Design partition keys carefully**: Distribute data evenly across partitions
3. **Use composite keys**: Leverage sort keys for efficient queries
4. **Create GSIs strategically**: Support different access patterns
5. **Use batch operations**: Reduce API calls for multiple items
6. **Implement pagination**: For large result sets use pagination
7. **Use transactions**: For operations that must be atomic
8. **Avoid scans**: Prefer queries with proper indexes
9. **Handle conditional writes**: Prevent race conditions
10. **Use proper error handling**: Handle exceptions like ProvisionedThroughputExceeded

## Common Patterns

### Conditional Operations
PutItemEnhancedRequest request = PutItemEnhancedRequest.builder(table)
.item(customer)
.conditionExpression("attribute_not_exists(customerId)")
.build();

table.putItemWithRequestBuilder(request);


### Pagination
ScanEnhancedRequest request = ScanEnhancedRequest.builder()
.limit(100)
.build();

PaginatedScanIterable<Customer> results = table.scan(request);
results.stream().forEach(page -> {
// Process each page
});


## Performance Considerations

- Monitor read/write capacity units
- Implement exponential backoff for retries
- Use proper pagination for large datasets
- Consider eventual consistency for reads
- Use ReturnConsumedCapacity to monitor capacity usage

## Related Skills

- aws-sdk-java-v2-core - Core AWS SDK patterns
- spring-data-jpa - Alternative data access patterns
- unit-test-service-layer - Service testing patterns
- unit-test-wiremock-rest-api - Testing external APIs

## References

- [AWS DynamoDB Documentation](https://docs.aws.amazon.com/dynamodb/)
- [AWS SDK for Java Documentation](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/)
- [DynamoDB Examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb)
- [LocalStack for Testing](https://docs.localstack.cloud/user-guide/aws/)

For detailed implementations, see the references folder:
- [Entity Mapping Reference](references/entity-mapping.md)
- [Advanced Operations Reference](references/advanced-operations.md)
- [Spring Boot Integration Reference](references/spring-boot-integration.md)
- [Testing Strategies](references/testing-strategies.md)

How to Use This Skill Unit

Option A: Project-Specific (Recommended)

  1. Click "Download" above
  2. In your project, create the directory: .agent/skills/aws-sdk-java-v2-dynamodb/
  3. Save the file as SKILL.md
  4. The agent will automatically discover the skill based on its description.

Option B: Global Installation (All Agents)

Save the file to these locations to make it available across all projects:

  • Claude Code: ~/.claude/skills/giuseppe-trisciuoglio/developer-kit/aws-sdk-java-v2-dynamodb/SKILL.md
  • Cursor: ~/.cursor/skills/giuseppe-trisciuoglio/developer-kit/aws-sdk-java-v2-dynamodb/SKILL.md
  • Antigravity: ~/.gemini/antigravity/skills/giuseppe-trisciuoglio/developer-kit/aws-sdk-java-v2-dynamodb/SKILL.md

🚀 Install with CLI:
npx skills add giuseppe-trisciuoglio/developer-kit

Read the Master Guide: Mastering Agent Skills

Recommended Rules

View more rules

Recommended Workflows

View more workflows

Recommended MCP Servers

View more MCP servers

Take It Further

Maximize your productivity with these powerful resources

📋

Define Your Standards

Set up coding standards to ensure this workflow produces consistent, high-quality results.

Browse Rules Library
📖

Master Workflows

Learn how to create custom workflows, use Turbo Mode, and build your automation library.

Complete Guide

How to use this Skill in Claude Code & Cursor

For Claude Code (CLI)

To use this skill in Claude Code, copy the rule content into your project's custom instructions or follow our Add-Skill CLI guide. This ensures Claude follows your standards during every code generation.

For Cursor & Windsurf

For Cursor or Windsurf, individual skills are best used in the "Rules for AI" section. This specific unit helps the agent avoid database & sql issues, leading to cleaner, more efficient code.

Why the skill format matters: the standardized Agent Skills format lets your AI agent load detailed instructions only when they are relevant, keeping your prompt clean while improving results.

Source & attribution

This skill is categorized under Database & SQL and is published by Giuseppe Trisciuoglio, maintained in giuseppe-trisciuoglio/developer-kit.

← Browse All Agent Skills
Sponsored AI assistant. Recommendations may be paid.