Enterprise Java

Spring Data MongoDB Tutorial

In today’s world it is very important to get the application up and running as soon as possible. The application should also be easy to develop and maintain.

Spring is such framework which provides the ease of integration with a lot of different frameworks which makes it easy to develop an application using Spring. One such integration is integration of Spring with MongoDB.

1. Introduction

In this tutorial we will discuss about the combination of most famous java framework “Spring” and the most famous NoSQL database “MongoDB”. MongoDB is a document based NoSQL database which stores the data in JSON like structure.

SpringData and MongoDB integration is provided by Spring for easy integration of the two and to provide an ease for developers without being bothered about writing multiple queries for insertion, update and deletion.

Below are some of the features that are provided by SpringData MongoDB project:

  1. SpringData allows the usage of @Configuration class and XML based configuration both.
  2. Data Access exception hierarchy of Spring is used for translation of exception.
  3. Integrated mapping between Java’s POJO and MongoDB’s document.
  4. MongoTemplate class that makes it easy to use common MongoDB operations.
  5. In Addition to MongoTemplate, MongoReader and MongoWriter classes for low-level of Mapping.

The best way to understand any technology is by practicing it and we are going to do the same now.

Let’s now do a simple program to understand Spring Data MongoDB in detail.

2. Technologies and Tools

Let us look at the technologies and tool used for building the program.

  1. Eclispe Oxygen.2 Release (4.7.2)
  2. Java – version 9.0.4
  3. Gradle – 4.6
  4. MongoDB server – 3.6
  5. MongoCompass – 3.6
  6. SpringDataMongoDB – 2.0.5-RELEASE

3. Project Structure

Our project structure will look as shown below.

Project Structure for SpringDataMongoDB

Gradle project structure will have above shown project structure. In case of pom.xml the project structure will differ slightly.

4. The Program

As part of this program we will try to accomplish below mentioned objectives.

  1. Save object to MongoDB
  2. Update object in MongoDB
  3. Remove object from MongoDB
  4. Get all objects from MongoDB

Let’s now understand all the components of the program. First of all we will start with the program dependencies and the jars that are needed for the program.

4.1 Gradle

We are using Gradle for build as part of the program. The build.gradle file will look as shown below.

build.gradle

apply plugin: 'java'
repositories {
    mavenCentral()
}

dependencies {
   compile group: 'org.springframework.data', name: 'spring-data-mongodb', version: '2.0.5.RELEASE'
   implementation 'com.google.guava:guava:23.0'
   testImplementation 'junit:junit:4.12'
}

In the above build.gradle file apply plugin: 'java' tells us the plugin that needs to be set. For us it is Java plugin.
repositories{} lets us know the repository from which the dependency should be pulled. We have chosen mavenCentral to pull the dependency jars. We can use jcenter also for pulling the respective dependency jars.
dependencies {} tag is used to provide necessary jar file details that should be pulled for the project.

4.2 Configuration for MongoDB

In order to use MongoDB configuration we need to implement AbstractMongoConfiguration class. The MongoConfig.java class will look as shown below. We are using annotations here instead of xml. But, even XML can also be used for the purpose of setting the configuration.

MongoConfig.java class implementation

package com.tutorial.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import com.mongodb.MongoClient;

@Configuration
public class MongoConfig extends AbstractMongoConfiguration {

	@Override
	public String getDatabaseName() {
		return "local";
	}

	@Override
	@Bean
	public MongoClient mongoClient() {
		return new MongoClient("127.0.0.1");
	}
}

The @Configuration is used to define the class MongoConfig.java as the configuration class. @Bean defines the MongoClient bean.

4.3 Model class

We will now look at the model class. We are using student.java as the model class which contains attributes for Student like Name and age. The Student.java model class is used for mapping POJO to the MongoDB collection.

Model class for Student

package com.tutorial.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "students")
public class Student {
	public Student(String studentName, int studentAge) {
		this.studentName = studentName;
		this.studentAge = studentAge;
	}
	@Id
	private String id;
	String studentName;
	int studentAge;

        public String getStudentName() {
		return studentName;
	}

	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}

	public int getStudentAge() {
		return studentAge;
	}

	public void setStudentAge(int studentAge) {
		this.studentAge = studentAge;
	}

	@Override
    public String toString() {
        return String.format(
                "Student[id=%s, studentName='%s', studentAge="+studentAge+"]",
                id, studentName);
    }    
}

@Document  defines the document. The property collection defines the collection which will be used for mapping with the collection. All the attributes that are mentioned as part of the collection should be available in the POJO class. @Id defines the id of the collection.

4.4 CRUD operations

To perform CRUD operations like saving data, updating data, removing data and getting the data from MongoDB we will use MongoOperations.

Now let’s look at the MongoDBPOperations.java class. This class contains implementation for all the methods for CRUD operations.

MongoDBPOperations class which will be used for performing CRUD operations

package com.tutorial;

import java.util.List;

import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import com.tutorial.model.Student;

public class MongoDBPOperations {

public void saveStudent(MongoOperations mongoOperation, Student student) {
		
		mongoOperation.save(student);
		System.out.println("Student saved successfully");
		// student object got created with id.
		System.out.println("student : " + student);
	}
	
	public void searchStudent(MongoOperations mongoOperation, String critera,String value) {
		// query to search student
		Query searchStudent = new Query(Criteria.where(critera).is(value));

		// find student based on the query
		Student resultStudent = mongoOperation.findOne(searchStudent, Student.class);
		System.out.println("Student found!!");
		System.out.println("Student details: " + resultStudent);
	}
	
	public void updateStudent(MongoOperations mongoOperation, String critera,String value, String updateCriteria, String updateValue) {
		// query to search student
		Query searchStudent = new Query(Criteria.where(critera).is(value));
		mongoOperation.updateFirst(searchStudent, Update.update(updateCriteria, updateValue),
				Student.class);
		System.out.println("Student got updated successfully");
	}
	public void getAllStudent(MongoOperations mongoOperation) {
		List listStudent = mongoOperation.findAll(Student.class);
		for(Student student:listStudent) {
		System.out.println("Student = " + student);
		}
	}
	public void removeStudent(MongoOperations mongoOperation, String critera,String value) {
		Query searchStudent = new Query(Criteria.where(critera).is(value));
		mongoOperation.remove(searchStudent, Student.class);
		System.out.println("Student removed successfully!! ");
	}
}

The most important class of a Java program is the class that contains the main method.


 

4.5 Application class

The main class which contains the main method is the Application.java class. We will use this class to call methods from MongoDBPOperations class.

Application class for calling methods of MongoDBPOperations class

package com.tutorial;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import com.tutorial.config.MongoConfig;
import com.tutorial.model.Student;


public class Application {
	
	public static void main (String[] args) {
		
    	   	
		// For Annotation
				ApplicationContext ctx = new AnnotationConfigApplicationContext(MongoConfig.class);
				MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
				MongoDBPOperations ops = new MongoDBPOperations();

				Student student = new Student("John", 15);
				
				//save student
				ops.saveStudent(mongoOperation, student);

				// get student based on search criteria
				ops.searchStudent(mongoOperation, "studentName", "John");
				
				//update student based on criteria
				ops.updateStudent(mongoOperation, "StudentName", "John", "studentAge", "18");
				// get student based on search criteria
				ops.searchStudent(mongoOperation, "studentName", "John");
				
				// get all the students
				ops.getAllStudent(mongoOperation);
				
				//remove student based on criteria
				ops.removeStudent(mongoOperation, "studentName", "John");
				// get all the students
				ops.getAllStudent(mongoOperation);
				

    }
	
	

}

Let us look a step by step operation that are performed in the Application.java class:

  1. We are creating ApplicationContext. This is due to the need of loading the configuration.
  2. In addition, MongoOperations object is created to load MongoTemplate bean.
  3. MongoDBOperations object provides access to the methods to perform different MongoOperation methods.
  4. Furthermore Create a Student object with Name John and Age as 15.
  5. We are calling the saveMethod of MongoDBOperations and we will pass the necessary parameters for saving the object in the Database.
  6. Similarly we are calling different methods of MongoDBOperations one by one.

4.6 Run the program

Finally let us now run the program as a java application. Right click on the Application.java -> Run as -> Java Application.

Following result will appear on the console.

Console output after running the program

Now let us comment the command for removing object. MongoDB will store data successfully.

Furthermore let us comment the line for removing the object as shown below.

Application class after commenting remove methods

package com.tutorial;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import com.tutorial.config.MongoConfig;
import com.tutorial.model.Student;


public class Application {
	
	public static void main (String[] args) {
		
    	   	
		// For Annotation
				ApplicationContext ctx = new AnnotationConfigApplicationContext(MongoConfig.class);
				MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
				MongoDBPOperations ops = new MongoDBPOperations();

				Student student = new Student("John", 15);
				
				//save student
				ops.saveStudent(mongoOperation, student);

				// get student based on search criteria
				ops.searchStudent(mongoOperation, "studentName", "John");
				
				//update student based on criteria
				ops.updateStudent(mongoOperation, "StudentName", "John", "studentAge", "18");
				// get student based on search criteria
				ops.searchStudent(mongoOperation, "studentName", "John");
				
				// get all the students
				ops.getAllStudent(mongoOperation);
				
				//remove student based on criteria
				//ops.removeStudent(mongoOperation, "studentName", "John");
				// get all the students
				//ops.getAllStudent(mongoOperation);
				

    }
	
	

}

As a result of change in the program let us re-run the program. The following will appear on the console.

Console when remove command is commented

As a result of commenting the remove command MongoDB will store the data and hence will look as shown below.

MongoDB Output after save and update command

5. Download the Eclipse project

This was an example of Spring Data MongoDB.

Download
You can download the full source code of this example here: SpringDataMongoDBTutorial.zip

Anand Kumar

Anand has graduated from Kuvempu University, India in Electronics and Instrumentation department. He has over 8 years of IT experience and is mainly involved in design and programming for websites and server side logic using Java oriented technologies like spring-boot, spring-data, spring-security, Hibernate, etc. He has worked with start-up companies and small business setup to Large Multinational companies.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button