引入Spring Data MongoDB

祝大家有美好的一天!

全新的“ Spring框架开发人员”流突然开始”了,这门课程在新学员和那些已经从“常规” Java和企业那里学到的知识的学员中都非常受欢迎。 因此,如果有趣的话,那就来我们这里公开课 ,当然,并分享有关该主题的有趣材料。

Spring Data MongoDB教程翻译
发表者Anand Kumar

走吧

在当今世界,尽快创建和运行应用程序非常重要。 同样,该应用程序应易于开发和维护。

Spring就是这样一种框架,它提供了与许多其他不同框架的轻松集成,从而简化了使用Spring的应用程序开发。 这样的集成之一就是Spring与MongoDB的集成。



1.简介

在本课程中,我们将讨论最著名的Spring java框架和最著名的NoSQL数据库管理系统(DBMS)MongoDB的组合。 MongoDB是面向文档的NoSQL DBMS,它以类似JSON的格式存储数据。
Spring提供了Spring Data和MongoDB的集成,以促进两者之间的交互以及开发人员的便利,从而消除了为插入,更新和删除编写许多查询的需要。

以下是Spring Data MongoDB项目提供的一些功能:

  1. Spring Data允许您同时使用@Configuration类和XML配置。
  2. 数据访问Spring异常层次结构用于转换异常。
  3. Java POJO和MongoDB文档之间的集成映射。
  4. MongoTemplate类,它简化了常见MongoDB操作的使用。
  5. 除了MongoTemplate,您还可以使用MongoReader和MongoWriter类进行低级渲染。

理解任何技术的最佳方法是在实践中使用它,而这正是我们现在要做的。

让我们创建一个简单的程序来了解有关Spring Data MongoDB的更多信息。

2.技术和工具

让我们看一下将用于创建程序的技术和工具。

  1. Eclispe Oxygen.2释放(4.7.2)
  2. Java-版本9.0.4
  3. 摇篮-4.6
  4. MongoDB服务器-3.6
  5. MongoCompass-3.6
  6. SpringDataMongoDB-2.0.5-发布

3.项目结构

我们项目的结构如下图所示。


Spring Data MongoDB的项目结构

gradle项目将具有上面显示的结构。 对于pom.xml,项目的结构将略有不同。

4.程序

作为该计划的一部分,我们将尝试完成以下任务。

  1. 在MongoDB中保存对象
  2. 在MongoDB中更新对象
  3. 从MongoDB中删除对象
  4. 从MongoDB检索所有对象

现在让我们分析程序的所有组件。 首先,我们将从程序所需的依赖项和jar文件开始。

4.1 gradle

我们使用Gradle作为该程序的一部分进行构建。 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' } 

build.gradlebuild.gradle文件中, build.gradle apply plugin: 'java'apply plugin: 'java'告诉您要安装哪个插件。 在我们的例子中,这是一个Java插件。

repositories{}标签报告应从中提取依赖关系的仓库。 我们选择了mavenCentral来提取依赖的jar文件。 我们还可以使用jcenter提取相应的相关jar文件。

dependencies {}标记用于提供有关需要为项目提取的jar文件的必要数据。

4.2 MongoDB的配置

要使用MongoDB配置,我们需要实现AbstractMongoConfiguration类。 MongoConfig.java类将如下所示。 在这里,我们使用注释而不是xml。 但是XML也可以用来配置配置。

MongoConfig.java类的实现

 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用于将MongoConfig.java类定义为配置类。 @Bean定义MongoClient

4.3模型类别

现在考虑模型的类别。 我们使用student.java作为模型类,其中包含Student的属性,例如Name和Age。 Student.java模型Student.java用于将POJO映射到MongoDB集合。

学生模特班

 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定义一个文档。 collection属性确定将用于匹配集合的集合。 必须在POJO类中访问被称为集合一部分的所有属性。 @Id定义集合标识符。

4.4 CRUD操作

要执行CRUD操作(创建,读取,更新,删除的缩写),例如从MongoDB保存,更新,删除和检索数据,我们将使用MongoOperations

现在让我们看一下MongoDBPOperations.java类。 此类包含CRUD操作的所有方法的实现。

将用于执行CRUD操作的MongoDBPOperations类

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

Java程序中最重要的类是包含main方法的类。

4.5应用类别

包含main方法的主要类是Application.java类。 我们将使用此类从MongoDBPOperations类中调用方法。

调用MongoDBPOperations类的方法的应用程序类

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

让我们逐步看一下Application.java类中执行的操作:

  1. 我们创建一个ApplicationContext 。 这是由于需要下载配置。
  2. 此外,还MongoOperations了一个MongoOperations对象来加载MongoTemplate组件。
  3. MongoDBOperations对象提供对用于执行各种MongoOperation操作的方法的访问。
  4. 此外,还创建了一个名为John和15岁的Student对象。
  5. 我们调用saveMethod类的saveMethod方法,并传递必要的参数以将对象保存在数据库中。
  6. 同样,我们MongoDBOperations调用各种MongoDBOperations方法。

4.6启动程序

最后,现在让我们将该程序作为Java应用程序运行。 右键单击Application.java-> Run as-> Java Application。

以下结果将出现在控制台中。


启动程序后的控制台输出

现在,让我们注释掉删除对象的命令。 MongoDB将成功存储数据。

另外,让我们注释掉删除对象的行,如下所示。

评论删除方法后的类申请

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

对程序进行更改后,让我们重新启动它。 控制台中将显示以下内容。


注释删除操作时的控制台

作为对delete命令的注释的结果,MongoDB将存储数据,因此将类似于以下所示。


保存和更新命令后的MongoDB输出

5.下载Eclipse项目

您可以在此处下载此示例的完整源代码

结束

与往常一样,我们在这里等待问题和评论,或者前往Yuri参加公开课程 ,在这里您不仅可以收听,而且可以四处询问。

Source: https://habr.com/ru/post/zh-CN430520/


All Articles