Updated March 29, 2023
Introduction to Spring Boot MongoDB
Spring Boot MongoDB is a part of umbrella spring data project that aims to provide a familiar and consistent spring based model for new datastores. As we all know, spring boot is an auto-configured microservice-based web framework with built-in features for database access and security purposes. With the help of spring boot, users can quickly create standalone applications without any configuration changes. Moreover, MongoDB being the most popular NoSQL database as data can be stored and retrieved with ease. Hence combining MongoDB with Spring boot will result in fast and secure, reliable applications that require minimum development time.
Start with Spring Boot MongoDB
Spring boot, being a quick production-ready application, interacts with MongoDB using the MongoTemplate class and MongoRepository interface. MongoTemplate class implements a set of ready-to-use APIs and is a good choice for operations such as update and aggregations. Moreover, it offers fine control over customized queries. On the other hand, the mongoRepository interface is used for basic queries that involve the field of the document, such as data creation, document view, etc.
For defining the dependency, in the pom.xml file:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>3.2.5</version>
</dependency>
Spring boot is the application framework for Java-based web applications and is based on the MVC framework. It is built on a spring framework, usually for REST APIs and requires fewer configurations.
It has 4 layers:
- Presentation Layer: View part of MVC that handles the front-end UI.
- Business Layer: Controller where business logics and validations are to be done.
- Persistence Layer: It translates business objects to database objects.
- Database Layer: CRUD (Create, Read, Update and Delete) operations are done here.
MongoDB handles a large amount of structured and unstructured data, making the database a choice for web applications. In addition, data in MongoDB is stored as BSON objects to make data retrieval easier.
Here we shall make use of spring initializr for quick setup of the project; we shall use two dependencies, MongoTemplate and MongoRepository, as said above.
Step 1: To create a Spring boot MongoDB project, use the URL https://start.spring.io/.
Step 2: Select Project as “Maven Project,” Language as “Java,” and the spring boot version required. Provide required group value, artifact value, name, and description of the project. The package name will be generated automatically based on Artifact value.
Step 3: Add “Spring Web” and “Spring Data MongoDB” dependencies to the project, and click on generate.
Step 4: On click of the generate button, a new project is created and downloaded automatically in a zip file.
Step 5: Unzip the project and import it as a project to Eclipse IDE or any other IDE that would work.
Step 6: As the Maven Dependencies are already set up, the user can add them manually if anything else is required.
Below is the pom.xml file that has been generated. Make sure to have a stable version of the Spring Boot Maven file.
Let us see how to create Spring Boot MongoDB REST APIs.
Step 1: By using the Spring Data MongoDB repository, we shall get access to data. Define Repository Interface first.
Step 2: Make a connection to the local instance of MongoDB, using the below syntax. Values change based on the users DB credentials.
#Local MongoDB config
spring.data.mongodb.authentication-database=sampleadmin
spring.data.mongodb.username=sample123
spring.data.mongodb.password=sample@123
spring.data.mongodb.database=sample_userDB
spring.data.mongodb.port=202107
spring.data.mongodb.host=localhost
# App
config server.port=8080
spring.application.name=SpringBootMongoDB
server.context-path=/user
The app runs on 8080 port.
Step 3: Defining APIs.
To get all users from MongoDB.
@RequestMapping(value = "", method = RequestMethod.GET)
public List<User_sample> getUsers() {
LOG.info("To get all users: ");
return userRepository.findAll();
}
Step 4: Add user.
@RequestMapping(value = "/createUser", method = RequestMethod.POST)
public User_sample addUsers(@RequestBody User_sample user)
{
LOG.info("Adding a user."); return userRepository.save(user);
}
Step 5: Likewise, we have for deleting user, getting details of a particular user, etc.
Spring Boot MongoDB Model Class
- It is a POJO-centric model to interact with MongoDB collection and have a Repository style data access layer.
- Spring config supports Java-based @Configuration class or XML namespace for replica sets and Mongo driver instance.
- MongoTemplate is a helper class which increases productivity by performing common Mongo operations that include integrated object mapping between POJOs and documents.
- Annotation-based mapping of metadata but is also extensible in supporting other metadata formats.
- Map Reduce integration and CDI support is given for repositories.
- Low-level mapping of MongoReader/ MongoWriter instance.
Conclusion
With this, we shall conclude the topic “Spring Boot MongoDB.” We have seen what Spring Boot MongoDB is all about and what is the use of MongoDB. We have also seen how Spring boot acts like an easy framework in building the Java Application along with integration with the MongoDB database. We have seen how dependency can be added to the pom.xml file. Using spring initializr, we have created a Spring application and integrated the required MongoDB dependencies in the initializr itself. We have also seen steps to implement the REST API methods with Spring boot applications.
Recommended Articles
This is a guide to Spring Boot MongoDB. Here we discuss the introduction, start with spring boot MongoDB and model class. You may also have a look at the following articles to learn more –