• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Spring Data MongoDB Example – MongoRepository

July 31, 2019 by javainterviewpoint Leave a Comment

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:

Folder Structure

  1. 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 
  2. 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>
  3. Create the Java classes SpringConfig.java, Employee.java, EmployeeDAO.java, EmployeeDAOImpl.java, EmployeeRepository.java and Application.java under com.javainterviewpoint folder.

Other interesting articles which you may like …

  • Spring Data JPA One To Many Foreign Key Example
  • Spring Data JPA One To One Foreign Key Example
  • Spring Data JPA Many To Many Foreign Key Example
  • Spring RESTful Web Services CRUD Example
  • Springfox Swagger 2 for Spring RESTful Web Services
  • Spring Boot CRUDRepository Example
  • Spring PropertyPlaceholderConfigurer Example
  • Spring JdbcTemplate Example + JdbcDaoSupport
  • Spring CRUD Example with JdbcTemplate + Maven + Oracle
  • @Autowired, @Resource, @Qualifier, @Inject Annotation
  • Spring Bean Life Cycle – Bean Initialization and Destruction
  • Static Factory Method & Instance Factory Method
  • How to create Spring Beans Using Spring FactoryBean
  • How to specify Spring Bean Reference and Spring Inner Bean
  • Spring Dependency Checking and Spring @Required Annotation

Spring Data MongoDB Example – MongoRepository

Spring Data MongoDB Example

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;
	    }
}

 

  1. @Configuration indicates that our SpringConfig class should be used by the Spring IoC container as a source of bean definitions.
  2. @ComponentScan scans for the stereotype annotations specified in @Controller, @Service, etc.. annotated classes.
  3. @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

Spring Data MongoDB 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

Spring Data MongoDB Update

Delete

MongoDB Delete

Filed Under: Java, Spring, Spring Core, Spring Data Tagged With: MongoDB, MongoRepository, Spring Data, Spring Data MongoDB, Spring Data MongoDB Example

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·