eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

eBook – Guide Spring Cloud – NPI (cat=Cloud/Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

1. Introduction

Amazon DynamoDB is one of the core services offered by AWS. It is widely used for building fast, scalable, and serverless applications. It provides a fully managed NoSQL database solution with single-digit millisecond performance at any scale. Unlike traditional relational databases, DynamoDB uses a key-value and document data model that encourages designing data access patterns up front.

In this tutorial, we’ll focus on one of DynamoDB’s most powerful features: querying data using a composite primary key, which combines a Partition Key and a Sort Key. We’ll walk through how this composite key model works and demonstrate how to efficiently query data using it with the AWS SDK for Java.

2. Understanding the Composite Key Model

DynamoDB supports two types of primary keys: a simple key (just a Partition Key) and a composite key, which combines a Partition Key and a Sort Key.

The Partition Key determines where the data is stored, while the Sort Key allows sorting and filtering within that partition. This model fits related data, like user orders, under a single key. For example, in a UserOrders table:

  • userId can be the Partition Key
  • orderDate can be the Sort Key

This setup makes it easy to retrieve all a user’s orders, sort them by date, or filter by time range, all with a single query.

3. Maven Dependency

To interact with DynamoDB from a Java application, we’ll use the AWS SDK for Java v2, which provides a modern, non-blocking API:

<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>dynamodb</artifactId>
    <version>2.31.26</version>
</dependency>

This gives us access to the DynamoDbClient and other necessary classes to run queries against our table.

4. Querying by Partition Key

The simplest and most common way to query data in DynamoDB is by using the Partition Key. When we query by Partition Key, DynamoDB returns all items sharing the same partition key value.

Let’s say our UserOrders table stores orders for multiple users, and we want to retrieve all orders placed by a single user. Since userId is our Partition Key, we can do this with a basic query:

QueryRequest queryRequest = QueryRequest.builder()
  .tableName("UserOrders")
  .keyConditionExpression("userId = :uid")
  .expressionAttributeValues(Map.of(
    ":uid", AttributeValue.builder().s("user1").build()
  )).build();

QueryResponse response = dynamoDbClient.query(queryRequest);

In the example above, we use the DynamoDbClient to execute the query. We built the request using the builder pattern, making it easy to construct complex requests. After executing the query, the results are returned in the QueryResponse object. To access the actual data, we use the items() method:

List<Map<String, AttributeValue>> items = response.items();

for (Map<String, AttributeValue> item : items) {
    System.out.println("Order item: " + item.get("item").s());
}

This list contains each item as a map of attribute names to values, which you can further process or convert into application-specific objects.

5. Querying with Partition Key and Sort Key

While querying by Partition Key alone might be useful, sometimes we need more precise filtering. We can achieve this by combining the Partition Key with conditions on the Sort Key. This allows us to filter results within a partition, for example, by a date range or a specific prefix.

Let’s say we want to retrieve all orders placed by user1 after January 1st, 2025. Since orderDate is our Sort Key, we can include a comparison in the keyConditionExpression:

QueryRequest queryRequest = QueryRequest.builder()
  .tableName("UserOrders")
  .keyConditionExpression("userId = :uid AND orderDate > :startDate")
  .expressionAttributeValues(Map.of(
    ":uid", AttributeValue.builder().s("user1").build(),
    ":startDate", AttributeValue.builder().s("2025-01-01").build()
  )).build();

QueryResponse response = dynamoDbClient.query(queryRequest);

In this query, we use the Partition Key and a condition on the Sort Key to narrow down the results. DynamoDB will only scan the partition for user1 and return items where the orderDate is after 2025-01-01. This approach is efficient because it avoids scanning unrelated data.

6. Common Range Key Conditions

DynamoDB supports several useful operators for filtering by the Sort Key. These allow us to fine-tune our queries within a partition by using standard comparison logic.

6.1. BETWEEN

We can use BETWEEN to retrieve items within a specific range. This is especially helpful when working with timestamps or dates:

QueryRequest queryRequest = QueryRequest.builder()
  .tableName("UserOrders")
  .keyConditionExpression("userId = :uid AND orderDate BETWEEN :from AND :to")
  .expressionAttributeValues(Map.of(
    ":uid", AttributeValue.builder().s("user1").build(),
    ":from", AttributeValue.builder().s("2024-12-01").build(),
    ":to", AttributeValue.builder().s("2024-12-31").build()
  )).build();

This will return all orders placed by user1 in December 2024.

6.2. BEGINS_WITH

If our Sort Key is a string (like a formatted date), we can query all items that start with a specific prefix. This is helpful for grouping by year, month, or any string-based prefix.

QueryRequest queryRequest = QueryRequest.builder()
  .tableName("UserOrders")
  .keyConditionExpression("userId = :uid AND begins_with(orderDate, :prefix)")
  .expressionAttributeValues(Map.of(
    ":uid", AttributeValue.builder().s("user1").build(),
    ":prefix", AttributeValue.builder().s("2025-01").build()
  )).build();

This will return all orders placed in January 2025.

7. Handling Pagination in Queries

DynamoDB limits the size of each query response to 1 MB of data. If our query matches more than that, DynamoDB returns a LastEvaluatedKey in the response, which we can use to continue fetching the next page of results.

To handle this, we should paginate through the results in a loop:

List<Map<String, AttributeValue>> allItems = new ArrayList<>();
Map<String, AttributeValue> lastKey = null;

do {
    QueryRequest.Builder requestBuilder = QueryRequest.builder()
      .tableName("UserOrders")
      .keyConditionExpression("userId = :uid")
      .expressionAttributeValues(Map.of(
        ":uid", AttributeValue.fromS(userId)
      ));

    if (lastKey != null) {
        requestBuilder.exclusiveStartKey(lastKey);
    }

    QueryResponse response = dynamoDb.query(requestBuilder.build());
    allItems.addAll(response.items());
    lastKey = response.lastEvaluatedKey();
} while (lastKey != null && !lastKey.isEmpty());

return allItems;

<This pattern ensures we retrieve all matching items, regardless of how many are returned per page. It’s useful when querying large partitions or doing report-style exports.

8. Conclusion

DynamoDB’s composite key model gives us a powerful way to organize and retrieve data efficiently. Using a Partition Key together with a Range Key allows us to organize related data and create efficient, scalable access patterns for high-performance applications.

In this article, we explored how to query a table using just the Partition Key and how to enhance those queries by including the Range Key to filter results within a partition.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
eBook – eBook Guide Spring Cloud – NPI (cat=Cloud/Spring Cloud)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments