How to integrate Spring boot and mongodb
In this article, we will demonstrate how to connect Spring Data with Mongodb and create a small REST service with Spring Boot and MongoDB.
MongoDB is a open source and document-oriented NoSQL database that stores data in JSON form. The main advantage of using mongodb is it is used for high volume data storage.
The commonly used terms which we used in spring data mongodb are:
1. Database: It is container of collections like in RDBMS contains so many tables in it.
2. Collection: It is equivalent to tables in relational database(mysql).
3. Document: It is equivalent to rows in RDBMS. It is single record in collection.
4. Fields: It is equivalent to columns in RDBMS having a key value pair
Tools and technologies used
1. Firstly install mongodb in your local system according to OS.
2. JDK 8
3. Intellij
4. Maven is need to be installed in your system.
5. Postman which is need to hit the rest api.
There are two approaches through which we connect springboot java to MongoDB database:
1. Mongo Repository
2. Mongo Template
We will used Mongo Repository for integration. MongoRepository provide us common functionalities and it is similar to JPA Repository. It is easy to use and implement than mongo template.
Lets get started, we will make use of Spring Initializr tool for quickly setting up the project. We will use just one dependency as shown below:
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
</dependencies>
Now we will create a simple model class of Users Information. We have a simple model class
User.java
@Document(collection = "user")
public class User {
@Id
private String userId;
private String name;
private String email;
private long rollno;
## Constructors
## Setters and getters
## tostring
}
@Document annotation is used for creating and representing the collection name..It is used for the same purpose with @Entity annotation in JPA.
@Id is used for mark fields as identity purpose. It is used like we represent primary key in jpa.
Create a interface which extends MongoRepository. This will give us access to all the CRUD operations. Now you can easily add and remove element from your Mongodb collection.
UserRepository.java
@Repository
public interface UserRepository extends MongoRepository<User, String> {
Student findByRollNumber(long rollno);
Student findByEmail(String email);
}
Now Setup a connection between mongo and springboot. To connect to the mongoDB database, go to the Resouces directory and edit or create application.properties file according to this given below:
#server
server.port=8081
#mongodb
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=test
Now, we create the User service. It contains four methods which is used for save, update, getall ,getbyelement and delete the users.
public interface UserService {
List<User> findAll();
Student findByEmail(String email);
void saveOrUpdateUser(User user);
void deleteUser(String id);
}
Create a service layer class
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public List<User> findAll() {
return userRepository.findAll();
}
@Override
public User findByEmail(String email) {
return userRepository.findByEmail(email);
}
@Override
public void saveOrUpdateUser(User user) {
userRepository.save(user);
}
@Override
public void deleteUser(String id) {
userRepository.deleteById(id);
}
}
Finally, we can create the REST controller
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping(value = "/")
public List<User> getAllUsers() {
return userService.findAll();
}
@GetMapping(value = "/byEmail/{email}")
public User getUserByEmail(@PathVariable("email") String email) {
return userService.findByEmail(email);
}
@PostMapping(value = "/save")
public ResponseEntity<?> saveOrUpdateUser(@RequestBody User user) {
userService.saveOrUpdateUser(user);
return new ResponseEntity("User added successfully", HttpStatus.OK);
}