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:
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:
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:
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:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
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:
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:
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.
1. Introduction
AWS Lambda is a serverless computing service provided by Amazon Web Services and WS DynamoDB is a NoSQL database service also provided by Amazon.
Interestingly, DynamoDB supports both document store and key-value store and is fully managed by AWS.
Before we start, note that this tutorial requires a valid AWS account (you can create one here). Also, it’s a good idea to first read the AWS Lambda with Java article.
2. Maven Dependencies
To enable lambda we need the following dependency which can be found on Maven Central:
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.2.1</version>
</dependency>
To use different AWS resources we need the following dependency which also can also be found on Maven Central:
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>3.11.0</version>
</dependency>
And to build the application, we’re going to use the Maven Shade Plugin:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
3. Lambda Code
There are different ways of creating handlers in a lambda application:
- MethodHandler
- RequestHandler
- RequestStreamHandler
We will use RequestHandler interface in our application. We’ll accept the PersonRequest in JSON format, and the response will be PersonResponse also in JSON format:
public class PersonRequest {
private int id;
private String firstName;
private String lastName;
private int age;
private String address;
// standard getters and setters
}
public class PersonResponse {
private String message;
// standard getters and setters
}
Next is our entry point class which will implement RequestHandler interface as:
public class SavePersonHandler implements RequestHandler<PersonRequest, PersonResponse> {
private AmazonDynamoDB amazonDynamoDB;
private String DYNAMODB_TABLE_NAME = "Person";
private Regions REGION = Regions.US_WEST_2;
public PersonResponse handleRequest(PersonRequest personRequest, Context context) {
this.initDynamoDbClient();
persistData(personRequest);
PersonResponse personResponse = new PersonResponse();
personResponse.setMessage("Saved Successfully!!!");
return personResponse;
}
private void persistData(PersonRequest personRequest) throws ConditionalCheckFailedException {
Map<String, AttributeValue> attributesMap = new HashMap<>();
attributesMap.put("id", new AttributeValue(String.valueOf(personRequest.getId())));
attributesMap.put("firstName", new AttributeValue(personRequest.getFirstName()));
attributesMap.put("lastName", new AttributeValue(personRequest.getLastName()));
attributesMap.put("age", new AttributeValue(String.valueOf(personRequest.getAge())));
attributesMap.put("address", new AttributeValue(personRequest.getAddress()));
amazonDynamoDB.putItem(DYNAMODB_TABLE_NAME, attributesMap);
}
private void initDynamoDbClient() {
this.amazonDynamoDB = AmazonDynamoDBClientBuilder.standard()
.withRegion(REGION)
.build();
}
}
Here when we implement the RequestHandler interface, we need to implement handleRequest() for the actual processing of the request. As for the rest of the code, we have:
- PersonRequest object – which will contain the request values passed in JSON format
- Context object – used to get information from the lambda execution environment
- PersonResponse – which is the response object for the lambda request
When creating an AmazonDynamoDB object, we’ll first create a new instance of builder with all defaults set. Note that the region is mandatory.
To add items in the DynamoDB table, we’ll create a Map of key-value pairs that represent the item’s attributes and then we can use putItem(String, Map<String, AttributeValue>).
We don’t need any predefined schema in the DynamoDB table, we just need to define the Primary Key column name, which is “id” in our case.
4. Building the Deployment File
To build the lambda application, we need to execute the following Maven command:
mvn clean package shade:shade
The Lambda application will be compiled and packaged into a jar file under the target folder.
5. Creating the DynamoDB Table
Follow these steps to create the DynamoDB table:
- Login to AWS Account
- Click “DynamoDB” which can be located under “All Services”
- This page will show DynamoDB Dashboard
- Click the “Tables” link
- This page will show already created DynamoDB tables (if any)
- Click the “Create table” button
- Provide “Table name” as “Person” and “Partition key” as “id” with its datatype as “Number”
- Click on the “Create table” button
- The table will be created
6. Creating the Lambda Function
Follow these steps to create the Lambda function:
- Login to AWS Account
- Click “Lambda” which can be located under “All Services”
- This page will show already created Lambda Functions (if any)
- Click the “Create function” button
- Select the “Author from scratch” option
- Provide “Function name” as “SavePerson” and “Runtime” as “Java 8 on Amazon Linux 2” and “Architecture” as “x86_64”
- In “Execution role” select “Use an existing role”. Select the IAM role created for lambda execution. Ensure the role has DynamoDB grants in it.
- Click on “Create function”
- This page will show the newly created “SavePerson” function
- Under the “Code” tab
- In the “Code source” section click on the “Upload from” button
- From the dropdown select “.zip or .jar file” and upload the jar file of the lambda application
- In the “Runtime settings” section click on the “Edit” button
- This page will show the Runtime settings. Here change the “Handler” to “com.baeldung.lambda.dynamodb.SavePersonHandler” and click on “Save”
- The message “Successfully updated the function SavePerson.” will appear
7. Testing the Lambda Function
The next step is to test the lambda function:
- Click the “Test” tab
- Provide “Event name” as “TestEvent”
- In the “Event JSON” window provide the below JSON input :
{
"id": 1,
"firstName": "John",
"lastName": "Doe",
"age": 30,
"address": "United States"
}
- Click the “Test“ button
- The below output will be displayed on the screen:
{
"message": "Saved Successfully!!!"
}
- We also need to check in DynamoDB that the record is persisted:
- Go to “DynamoDB” Management Console
- Click on “Tables”
- Select the table “Person”
- Click on the “Explore table items” tab
- Under “Items returned” you can see the person’s details which were being passed in request to the lambda application
- So the request is successfully processed by our lambda application
8. Conclusion
In this quick article, we have learned how to create a Lambda application with DynamoDB and Java 8. The detailed instructions should give you a head start in setting everything up.
