MongoDB is a popular NoSQL database that is widely used for modern web applications. Spring Boot is a powerful framework for building Java applications and is the perfect choice for creating a backend for a MongoDB powered application. In this blog post, we will look at how to connect MongoDB to a Spring Boot application and start working with it.
Prerequisites
To follow along with this tutorial, you will need to have the following prerequisites:
- Java 8 or higher installed on your computer
- Spring Boot CLI installed on your computer
- MongoDB installed on your computer or a MongoDB Atlas account.
Creating a Spring Boot Project
To create a Spring Boot project, we will use the Spring Initializer. Open your web browser and go to the following URL: https://start.spring.io/.
In the Spring Initializer, select the following options:
- Project: Maven Project
- Language: Java
- Spring Boot: 2.4.0 (or the latest version)
- Packaging: Jar
- Java: 8 (or the latest version)
Next, select the following dependencies:
- Spring Data MongoDB
- Lombok (Optional)
Click on the “Generate” button to download the project. Extract the contents of the ZIP file to your desired location on your computer.
Connecting to MongoDB
To connect to MongoDB, we need to add the following properties to the application.properties file located in the resources folder of your project:
spring.data.mongodb.database=<database_name>
spring.data.mongodb.host=<hostname>
spring.data.mongodb.port=<port_number>
spring.data.mongodb.username=<username>
spring.data.mongodb.password=<password>
Replace the placeholders in the properties file with the actual values for your MongoDB instance.
Creating a MongoDB Repository
To start working with MongoDB in your Spring Boot application, we need to create a repository. A repository is a class that contains methods for performing CRUD (Create, Read, Update, Delete) operations on the database. To create a MongoDB repository, follow these steps:
- Create a new Java class in the com.example.demo package (or your desired package)
- Annotate the class with
@Repository
- Extend the MongoRepository interface
- Specify the type of the entities and the type of the ID field that the repository will manage.
Here is an example of a MongoDB repository:
package com.example.demo;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends MongoRepository<User, String> {
}
In this example, the UserRepository is a repository that will manage User entities with a String ID field.
Creating a MongoDB Entity
To create a MongoDB entity, we need to create a Java class that represents a document in the MongoDB collection. To create a MongoDB entity, follow these steps:
- Create a new Java class in the com.example.demo package (or your desired package)
- Annotate the class with
@Document
- Add fields to the class that represent the document’s attributes
- Annotate the fields with
@Id
if the field is the primary key of the document.
Here is an example of a MongoDB entity:
package com.example.demo;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class User {
@Id
private String id;
private String firstName;
private String lastName;
private int age;
// getters and setters
}
In this example, the User entity represents a user document in the MongoDB collection. The @Id
annotation indicates that the id
field is the primary key of the document.
Creating a REST Endpoint
To create a REST endpoint for the MongoDB repository, we need to create a REST controller. A REST controller is a class that contains methods that handle HTTP requests. To create a REST controller, follow these steps:
- Create a new Java class in the com.example.demo package (or your desired package)
- Annotate the class with
@RestController
- Autowire the MongoDB repository into the class using the
@Autowired
annotation - Add methods to the class that handle HTTP requests and use the repository to perform CRUD operations on the database.
Here is an example of a REST controller:
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("/users")
public List<User> getAllUsers() {
return userRepository.findAll();
}
@PostMapping("/users")
public User createUser(@RequestBody User user) {
return userRepository.save(user);
}
@GetMapping("/users/{id}")
public User getUserById(@PathVariable(value = "id") String userId) {
return userRepository.findById(userId).orElse(null);
}
@PutMapping("/users/{id}")
public User updateUser(@PathVariable(value = "id") String userId,
@RequestBody User userDetails) {
User user = userRepository.findById(userId).orElse(null);
if (user != null) {
user.setFirstName(userDetails.getFirstName());
user.setLastName(userDetails.getLastName());
user.setAge(userDetails.getAge());
user = userRepository.save(user);
}
return user;
}
@DeleteMapping("/users/{id}")
public void deleteUser(@PathVariable(value = "id") String userId) {
userRepository.deleteById(userId);
}
}
In this example, the UserController class is annotated with @RestController
, which means it is a REST controller. The @Autowired
annotation is used to autowire the UserRepository into the class so that it can be used to perform CRUD operations on the database.
The class contains several methods that handle HTTP requests. The @GetMapping
, @PostMapping
, @PutMapping
, and @DeleteMapping
annotations are used to map HTTP GET, POST, PUT, and DELETE requests to the appropriate methods.
For example, the getAllUsers
method is mapped to the /users
endpoint and returns a list of all users in the database. The createUser
method is mapped to the /users
endpoint and creates a new user in the database. The getUserById
method is mapped to the /users/{id}
endpoint and returns a user with the specified ID. The updateUser
method is mapped to the /users/{id}
endpoint and updates a user with the specified ID. The deleteUser
method is mapped to the /users/{id}
endpoint and deletes a user with the specified ID.
Conclusion
In this blog post, we have seen how to connect MongoDB to a Spring Boot application. We have created a MongoDB entity, a MongoDB repository, and a REST endpoint to perform CRUD operations on the database. With this setup, you can start building your application and take advantage of the powerful features of MongoDB and Spring Boot.