In this Spring Data MongoDB Example, we will build a Simple Spring Application and perform CRUD operations on the Mongo Database with the help of Spring Data MongoDB and MongoRepository. MongoDB is a document-based NoSQL database, providing high performance and high availability. Spring provides seamless integration with the Mongo database through Spring Data MongoDB which is a part of Spring Data project.
Let’s create an Employee management application which has abilities to create a new employee, update the existing employee, get a particular employee/ all employee and finally delete the existing employee.
Creating Collection and Employee Document
Use the Database which you have already created
use mydb;
In MongoDB, we can relate the Collections to a Table in the relational database, Let’s create the Employee Collection which holds the employee details
db.createCollection('employee');
Once we have created the Employee Collection, we need to add some data employee data into the collection, each of them is called as Document and contains the firstname and lastname of the employee. Just execute the below command to insert 3 Employee documents.
db.employee.insert( {firstname : "John", lastname: "Smith"}, {firstname : "David", lastname: "Jones"}, {firstname : "Paul", lastname: "Scholes"});
In order to use Spring Data MongoDB in our project, we must add the below spring-data-mongodb in our pom.xml
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>2.1.9.RELEASE</version>
</dependency>
Folder Structure:
- Create a simple Maven Project “SpringMongoDBExample” by selecting maven-archetype-quickstart and create a package for our source files “com.javainterviewpoint” under src/main/java
- Now add the following dependency in the POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javainterviewpoint</groupId> <artifactId>SpringMongoDBExample</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>SpringMongoDBExample</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.1.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.1.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>2.1.9.RELEASE</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </pluginManagement> </build> </project>
- Create the Java classes SpringConfig.java, Employee.java, EmployeeDAO.java, EmployeeDAOImpl.java, EmployeeRepository.java and Application.java under com.javainterviewpoint folder.
Spring Data MongoDB Example – MongoRepository
Defining the Model – Employee.java
package com.javainterviewpoint; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(value = "employee") public class Employee { @Id private String id; private String firstname; private String lastname; public Employee() { super(); } public Employee(String firstname, String lastname) { super(); this.firstname = firstname; this.lastname = lastname; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } @Override public String toString() { return "Employee [firstname=" + firstname + ", lastname=" + lastname + "]"; } }
We have created the Employee class with two attributes firstname and lastname and their corresponding getters and setters
The id attribute is for the internal use of the MongoDB, the @Id annotation on top of it informs Spring that this field will be used as the primary identifier.
MongoDB stores the data in Collection, Spring Data MongoDB automatically maps the Model (Employee class) with the Collection (Employee) only when the name of the model and collection are same, however, if it is different then we need to use @Document annotation to point the right Collection.
Adding the Repository – MongoRepository
We simply have created an interface EmployeeRepository which in turn extends MongoRepository that’s all we have to do Spring Data will automatically create an implementation in the runtime.
MongoRepository will by default provide you with the generic methods like save(), findAll(), insert(), etc.. Out-of-the-box we can also add our custom methods and Spring Data has the query builder mechanism built in which strips the prefixes find…By, read…By, and get…By, We have used the same mechanism and built our custom method findByFirstname()
package com.javainterviewpoint; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; @Repository public interface EmployeeRepository extends MongoRepository<Employee, String> { public Employee findByFirstname(String firstname); }
Creating the Configuration file
package com.javainterviewpoint; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import com.mongodb.MongoClient; @Configuration @ComponentScan (basePackages = {"com.javainterviewpoint"}) @EnableMongoRepositories (basePackages = {"com.javainterviewpoint"}) public class SpringConfig { @Bean public MongoDbFactory mongoDbFactory() { MongoClient mongoClient = new MongoClient("localhost", 27017); return new SimpleMongoDbFactory(mongoClient, "mydb"); } @Bean public MongoTemplate mongoTemplate() { MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory()); return mongoTemplate; } }
- @Configuration indicates that our SpringConfig class should be used by the Spring IoC container as a source of bean definitions.
- @ComponentScan scans for the stereotype annotations specified in @Controller, @Service, etc.. annotated classes.
- @EnableMongoRepositories scans the current package or packages mentioned in the basePackages attribute for any interface that extends Spring Data interface
In the configuration file, we will be creating two beans
- MongoDbFactory – This Factory Bean will create an instance of the MongoDbFactory. We will be passing the URL and port information to the MongoClient and which in turn will be passed to the constructor of the SimpleMongoDbFactory along with database name.
- MongoTemplate – MongoTemplate provides the Out-of-the-box methods to Spring Data MongoDB, we just need to pass the mongoDbFactory instance which we have created above. MongoRepository behind scenes uses the MongoTemplate to query the Mongo database.
Equivalent XML Configuration
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd"> <mongo:mongo-client id="mongoClient" host="localhost" port="27017" /> <mongo:db-factory id="mongoDbFactory" dbname="employee" mongo-ref="mongoClient" /> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongoDbFactory" /> </bean> <context:annotation-config /> </beans>
Create Data Access Layer (EmployeeDao)
package com.javainterviewpoint; import java.util.List; public interface EmployeeDao { public void createEmployee(Employee employee); public Employee getEmployeeByFirstName(String firstname); public List<Employee> getAllEmployees(); public void updateEmployee(Employee employee); public void deleteEmployee(String id); }
EmployeeDao is a simple interface to perform CRUD Operation, implementation will be provided by EmployeeDaoImpl class.
DAO Implementation (EmployeeDaoImpl)
package com.javainterviewpoint; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class EmployeeDaoImpl implements EmployeeDao { @Autowired public EmployeeRepository employeeRepository; @Override public void createEmployee(Employee employee) { employeeRepository.insert(employee); } @Override public Employee getEmployeeByFirstName(String firstname) { return employeeRepository.findByFirstname(firstname); } public Employee getEmployeeById(String id) { Optional<Employee> e = employeeRepository.findById(id); return e.get(); } @Override public List<Employee> getAllEmployees() { return employeeRepository.findAll(); } @Override public void updateEmployee(Employee employee) { employeeRepository.save(employee); } @Override public void deleteEmployee(String id) { employeeRepository.deleteById(id); } }
We have autowired EmployeeRepository in our implementation class which enables us to perform CRUD Operation using the predefined methods provided by Spring Data repositories.
Standalone Application
package com.javainterviewpoint; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.AbstractApplicationContext; public class Application { public static void main( String[] args ) { AbstractApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); EmployeeDaoImpl employeeDaoImpl = (EmployeeDaoImpl) context.getBean("employeeDaoImpl"); // Create Employee Employee employee1 = new Employee("Tom","Jerry"); employeeDaoImpl.createEmployee(employee1); // Get Employee by FirstName Employee employee2 = employeeDaoImpl.getEmployeeByFirstName("Tom"); System.out.println("*** Get Employee By FirstName ***"); System.out.println("First Name : "+employee2.getFirstname()); System.out.println("Last Name : "+employee2.getLastname()); // Get all Employees List<Employee> employeeList = employeeDaoImpl.getAllEmployees(); System.out.println("*** Get All Employees ***"); for(Employee emp : employeeList) { System.out.println("First Name : "+emp.getFirstname()); System.out.println("Last Name : "+emp.getLastname()); System.out.println("#######################################"); } // Update Employee - Read from DB and Update the Employee Employee employee3 = employeeDaoImpl.getEmployeeById("5d3ea548169b493d773327c1"); employee3.setLastname("Jonny"); employeeDaoImpl.updateEmployee(employee3); // Delete Employee employeeDaoImpl.deleteEmployee("5d3ecb690594262d20a96e6e"); context.close(); } }
- AnnotationConfigApplicationContext registers all the beans generated by the configuration class (SpringConfig.java) at Spring runtime.
- Use the getBean() method to get an instance of the EmployeeDaoImpl bean
- Once we obtained the instance of the EmployeeDaoImpl class, perform the CRUD Operation by calling the createEmployee(), getEmployeeByFirstName(), getAllEmployees(), updateEmployee and deleteEmployee() methods of the EmployeeServiceImpl Class.
Output:
Create
Read
*** Get Employee By FirstName *** First Name : Tom Last Name : Jerry *** Get All Employees *** First Name : John Last Name : Smith ####################################### First Name : David Last Name : Jonny ####################################### First Name : Paul Last Name : Scholes ####################################### First Name : Tom Last Name : Jerry #######################################
Update
Delete
Leave a Reply