📜 ⬆️ ⬇️

Meet Spring Data MongoDB

Good day to all!

A new flow “Developer on the Spring Framework” started, “suddenly”, this course turned out to be very popular among new students, as well as those who have already learned how to use “regular” java and enterprise. So, if you are interested, come to us for open lessons , and, of course, share interesting materials on the subject.

Translation of the Spring Data MongoDB Tutorial article
The author of the article is Anand Kumar
')
Go!

In the modern world it is very important to create and launch an application as soon as possible. Also, the application should be simple to develop and easy to maintain.

Spring is just such a framework that provides ease of integration with many other different frameworks, which makes it easy to develop an application using Spring. One such integration is Spring integration with MongoDB.



1. Introduction

In this lesson we will discuss the combination of the most famous java-framework "Spring" and the most famous NoSQL database management system (DBMS) "MongoDB". MongoDB is a document-oriented NoSQL DBMS that stores data in a JSON-like format.
Spring Data and MongoDB integration is provided by Spring to facilitate the interaction of both and the convenience of developers, eliminating the need to write multiple queries for insertion, update, and deletion.

The following are some of the features provided by the Spring Data MongoDB project:

  1. Spring Data allows you to use both the @Configuration class and the XML configuration.
  2. The Data Access Spring exception hierarchy is used to translate the exception.
  3. Integrated mapping between a Java POJO and a MongoDB document.
  4. The MongoTemplate class, which simplifies the use of common MongoDB operations.
  5. In addition to MongoTemplate, you can use the MongoReader and MongoWriter classes for low-level mapping.

The best way to understand any technology is to use it in practice, and this is exactly what we are going to do now.

Let's create a simple program to learn more about Spring Data MongoDB.

2. Technologies and tools

Let's look at the technologies and tools that we will use to create 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

The structure of our project will look like the one below.


Project structure for Spring Data MongoDB

The gradle project will have the structure shown above. In the case of pom.xml, the project structure will be slightly different.

4. Program

As part of this program, we will try to perform the following tasks.

  1. Saving an object in MongoDB
  2. Updating an object in MongoDB
  3. Deleting an object from MongoDB
  4. Getting all the objects from MongoDB

Let's now analyze all the components of the program. First of all, we will start with the dependencies and jar files required for the program.

4.1 Gradle

We use Gradle for assembly as part of the program. The build.gradle file will look like the one below.

 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 build.gradle in the apply plugin: 'java' line apply plugin: 'java' it tells you which plugin to install. In our case, this is a Java plugin.

The repositories{} tag reports the repository from which dependencies should be pulled. We chose mavenCentral to pull up dependent jar files. We can also use jcenter to pull the corresponding dependent jar files.

The dependencies {} tag is used to provide the necessary data about the jar files that need to be pulled up for the project.

4.2 Configuration for MongoDB

To use the MongoDB configuration, we need to implement the AbstractMongoConfiguration class. The MongoConfig.java class will look like the one below. Here we use annotations instead of xml. But XML can also be used to customize the configuration.

Implementing the MongoConfig.java class

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

@Configuration used to define the MongoConfig.java class as a configuration class. @Bean defines a @Bean bin.

4.3 Model class

Now consider the model class. We use student.java as a model class that contains attributes for Student, such as Name and Age. The class model Student.java used to map the POJO to the MongoDB collection.

Student Model Class

 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 collection property determines the collection that will be used to match the collection. All attributes that are referred to as part of the collection must be available in the POJO class. @Id defines the collection id.

4.4 CRUD operations

To perform CRUD operations (abbr. From create, read, update, delete), such as saving, updating, deleting and retrieving data from MongoDB, we will use MongoOperations .

Now let's take a look at the MongoDBPOperations.java class. This class contains the implementation of all methods of CRUD operations.

The MongoDBPOperations class that will be used to perform 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 that contains the main method is the Application.java class. We will use this class to call methods from the MongoDBPOperations class.

Application class for calling methods of the 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's look step by step at the operations that are performed in the Application.java class:

  1. We create an ApplicationContext . This is due to the need to load the configuration.
  2. In addition, a MongoOperations object was MongoOperations to load the MongoTemplate component.
  3. The MongoDBOperations object provides access to methods for performing various MongoOperation operations.
  4. In addition, a Student object is created with the name John and age 15.
  5. We call the saveMethod method of the saveMethod class, and pass the necessary parameters to save the object in the database.
  6. Similarly, we MongoDBOperations various methods of MongoDBOperations one after another.

4.6 Running the program

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

The following result will appear in the console.


Console output after starting the program

Now let's comment out the command to delete the object. MongoDB will successfully store the data.

Also, let's comment out the line for deleting an object, as shown below.

Class application after commenting on removal 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); } } 

After making changes to the program, let's restart it. The following will appear in the console.


Console when the delete operation is commented out

As a result of commenting on the delete command, MongoDB will store the data and, therefore, will look as shown below.


MongoDB output after saving and updating command

5. Download the Eclipse project.

You can download the entire source code of this example here.

THE END

As always, we are waiting for questions and comments here or go to Yuri for an open lesson , where you can not only listen, but also ask around.

Source: https://habr.com/ru/post/430520/


All Articles