Spring Boot with AWS Dynamo DB
Writing this to share my learning with integrating the Spring Data JPA and AWS Dynamo DB. Used the docker image to run this example in my local.
This article for the person who already have the basic understanding on the Spring boot and spring data JPA.
AWS Dynamo local with docker
Install the docker in local and run the following command in local to run dynamoDB
docker run -p 8000:8000 amazon/dynamodb-local
check the dynamodb running in your local by the below command line.
aws2 dynamodb list-tables — endpoint-url http://localhost:8000
{
“TableNames”: []
}
Now Let’s configure the dynamo with Spring data JPA. Add the following as the dependency.
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.695</version>
</dependency>
<dependency>
<groupId>com.github.derjust</groupId>
<artifactId>spring-data-dynamodb</artifactId>
<version>5.1.0</version>
</dependency>
DynamoDB bean configuration
Load the endpoint, access-key and secret-key from the environment and create the AmazonDynamoDB Object. Look at the below sample snippet.
@Bean
public AmazonDynamoDB amazonDynamoDB(@Value("${aws.access-key}") String accessKey,
@Value("${aws.secret-key}") String secretKey,
@Value("${aws.dynamodb.endpoint}") String endpoint) {
return AmazonDynamoDBClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, null))
.build();
}
Enable the dynamoDb and scan the repositories using @EnableDynamoDBRepositories annoatation.
@EnableDynamoDBRepositories(basePackages = "package path which have Repository"
Entity creation
Using the below example UserDetails table to store and retrieve the details
@Data
@DynamoDBTable(tableName = "UserDetail")
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserDetail {
@DynamoDBHashKey
@DynamoDBAutoGeneratedKey
private String id;
@DynamoDBAttribute
private String name;
@DynamoDBAttribute
private String emailAddress;
}
Repository creation
@EnableScan
public interface UserDetailRepository extends CrudRepository<UserDetail, String> {
}
That’s it, all set. Just auto wire the repository where ever we want and make transaction in the table. Check it out the full code in https://gitlab.com/saravanastar/dynamo-sample
To create/drop tables automatically use the following configuration for the dynamoDb instead of the hibernate.ddl-auto
spring:
data:
dynamodb:
entity2ddl:
auto: create-drop
Author is writing the article for the first time. Do comment your thoughts and comments to improve these.