This article is part of the series. We will learn to use spring data and configure our database in MongoDB cloud.
In this series of tutorials, we are going to cover:
- Introduction and creating our Microservices (Part 1)
- Mongo DB cloud integration (Part 2)
- Deployment to CloudFoundry (Part 3))
- Deployment to AWS (Part 4)
Let’s get started,
Step 1: Add the Maven Dependencies
Spring Boot provides a very convenient spring-boot-starter-data-mongodb
project to add
the dependencies we need to buid our entities and DAO layer.
We are also adding lombok dependency, this helps us avoid boilerplate in our java classes. Ref: lombok
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
Step 2: Create Entity and the Repository
We are using Spring data which will generate the basic
repository for us just by extending CrudRepository
To avoid empty shopping item and to display the prowess of javax validation , let’s add a bunch of validation to the shopping item name.
@Data
@Document(collection="shopping-items")
public class ShoppingItem {
@Id
private String id;
@NotEmpty(message = "{shopping.list.mandatory}")
@Pattern(regexp = "[a-zA-Z0-9]*", message = "{shopping.list.alphanumeric}")
private String name;
}
Let’s add a validationMessages.properties
file in src/main/resources
.
shopping.list.alphanumeric=Shopping list name should contain alphanumeric text
shopping.list.mandatory=Shopping list name is mandatory
Step 3: Installing Mongo DB
For our database need with MongoDB, lets install MongoDB and start a database,
MongoDB community addition can be downloaded from here, https://www.mongodb.com/download-center/community
MongoDB default directories for data are , let’s create this to start mongo database.
- Windows - C:/data/db
- Mac - /data/db
Start Mongo DB with below command
.\mongod.exe
This starts the default database test
, let’s create a new database shopping-list
by running below command to open mongo db terminal
.\mongo.exe
use shopping-list
Now let’s add this new database properties in our application.yaml
data:
mongodb:
database: shopping-list
host: localhost
port: 27017
Step 4: Create Shopping List REST controller
Add a Repository that extends CrudRepository
public interface ShoppingListRepository extends CrudRepository<ShoppingItem, String> {
}
We created a basic REST controller in PART 1 of the series, let’s modify it will call to our repository.
We don’t have any business logic so let’s avoid a Service layer and add Repository calls in REST layer.
@RestController
@RequestMapping("/")
public class ShoppingListController {
@Autowired
public ShoppingListRepository shoppingRepo;
@GetMapping
public Iterable<ShoppingItem> getShoopingList() {
return shoppingRepo.findAll();
}
@GetMapping("/{id}")
public ShoppingItem getItem(@PathVariable String id) {
return shoppingRepo.findById(id).get();
}
@PutMapping
public ShoppingItem addShoppingList(@RequestBody @Valid ShoppingItem item) {
return shoppingRepo.save(item);
}
@DeleteMapping("/{id}")
public void deleteItem(@PathVariable String id) {
shoppingRepo.deleteById(id);
}
}
Step 5: Running the application
We are now ready to test our REST service with local MongoDB instance,
Let’s run our spring boot app, if you are not sure how to do that then please have alook at PART 1 of the series added in reference.
org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:2}] to localhost:27017
...
c.c.shoppinglist.Application: Started Application in 3.287 seconds (JVM running for 4.875)
Step 6: Testing the application
I prefer POSTMAN for testing the REST API but you can choose any other tool of your choice
We now test by adding to our list,
Make sure you have lombok installed otherwise you may see empty data coming in as Json Mapper will not be able to find getter setters for your POJO
https://projectlombok.org/setup/eclipse
PUT data with POSTMAN
Verify Validations are working
Verify the data in GET call
http://localhost:3024/shopping-list/
[{"id":"5ec410f1f595d85b487a9cc2","name":"Egg"},{"id":"5ec41247f963943db037e1fd","name":"Milk"}]
Verify data in MongoDB compass GUI installed with MongoDB,
Step 7: Create DB in MongoDB Cloud (Atlas)
Let’s create an account in MongoDB cloud https://cloud.mongodb.com/
Once you create your free account and login, create a free cluster, this will 2-3 minutes.
Once your cluster is ready , it will look like below
Click on the connect to create a connection, whitelist your IP address and provide a username-password,
Select your driver and copy the connection string,
Step 8: Create a spring profile and connect to MongoDB cloud
We have created our Mongo DB cloud, lets create a separate maven profile that we can use when connecting to cloud databasse.
Create a file application-cloud.yaml
in src/main/resources
We will use different port so it allow us to test both local and cloud db application profiles.
spring:
data:
mongodb:
uri: mongodb+srv://testuser:testpassword@shopping-list-cluster-vac4w.mongodb.net/test?retryWrites=true&w=majority
server:
port: 3025
We should configure Spring Boot to know profile to use,
We can either use Maven profiles and configure spring boot to make that profile active or directly use spring profile which is easier option. We will stick with spring profile for this tutorial.
Let’s duplicate our spring boot config,
Now let’s update the profile to activate correct spring profile,
You should see both application profile in Spring Tools,
You can now run both application and POST some data to cloud profile,
Remember cloud database profile is running at port 3025
We can verify this data in MongoDB cloud by going to our cluster,
We have reached the end of this PART in the series , we commit our changes and create a tag.
🙌🥂🎉🎉🍺 The GitHub repository for the demo application: https://github.com/avinash10584/shoppinglist-springboot-microservice/
For PART2
https://github.com/avinash10584/shoppinglist-springboot-microservice/tree/PART2
In next part of the series we will look at deployment and will work on deploying our application to pivotal cloudfoundry.