Spring Data MongoDB示例

Welcome to Spring Data MongoDB example. Spring Data MongoDB is one of the Spring projects for integrating Spring Framework with most widely used NoSQL database MongoDB.

欢迎使用Spring Data MongoDB示例。 Spring Data MongoDB是将Spring Framework与最广泛使用的NoSQL数据库MongoDB集成的Spring项目之一。

Spring Data MongoDB (Spring Data MongoDB)

One of the key benefit of using Spring is that it provides integration with most of the major frameworks that are used in enterprise application. For example, Spring ORM Hibernate Integration.

使用Spring的主要好处之一是它提供了与企业应用程序中使用的大多数主要框架的集成。 例如, Spring ORM Hibernate Integration 。

We will use latest version of Spring Framework and Spring Data MongoDB for our example project. Our final Spring Data MongoDB example project will look like below image.

对于示例项目,我们将使用最新版本的Spring Framework和Spring Data MongoDB。 我们最终的Spring Data MongoDB示例项目将如下图所示。

Spring Data MongoDB can be used in a simple application too, it’s not required to use Spring framework with it. Let’s see this with a simple Spring MongoDB example. For that all you need to include below dependencies in pom.xml file, it will automatically include the compatible MongoDB java driver through maven transitive dependencies.

Spring Data MongoDB也可以在一个简单的应用程序中使用,不需要与它一起使用Spring框架。 让我们用一个简单的Spring MongoDB示例来看看。 为此,您需要在pom.xml文件中包括以下依赖项,它将通过maven可传递依赖项自动包含兼容的MongoDB Java驱动程序。


	org.springframework.data
	spring-data-mongodb
	1.5.2.RELEASE

Spring Data MongoDB示例–模型Bean (Spring Data MongoDB Example – Model Bean)

We will have a simple model bean with some variables to be stored in MongoDB database.

我们将有一个简单的模型bean,其中包含一些要存储在MongoDB数据库中的变量。

Person.java

Person.java

package com.journaldev.spring.mongodb.model;

import org.springframework.data.annotation.Id;

public class Person {

	//id will be used for storing MongoDB _id
	@Id
	private String id;
	
	private String name;
	private String address;
	
	public Person(){}
	public Person(String i, String n, String a){
		this.id=i;
		this.name=n;
		this.address=a;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	
	@Override
	public String toString(){
		return id+"::"+name+"::"+address;
	}
}

It’s a simple java bean, however there are few important points that you should know.

这是一个简单的Java Bean,但是您应该了解的一些要点。

  1. We know that every document in MongoDB is required to have a primary key with name _id, we can either provide it or MongoDB will generate it for us. We can use org.springframework.data.annotation.Id annotation with a model bean variable to map it to _id field.

    我们知道MongoDB中的每个文档都必须具有名称为_id的主键,我们可以提供它,也可以由MongoDB为其生成。 我们可以将org.springframework.data.annotation.Id注释与模型bean变量一起使用,以将其映射到_id字段。
  2. If the field name is “id” then we don’t need to use the @Id annotation, however it’s best practice to use it. In above class, we could have skipped @Id annotation.

    如果字段名称是“ id”,则我们不需要使用@Id批注,但是最佳做法是使用它。 在上面的类中,我们可以跳过@Id注释。
  3. You should always have id field in the bean, otherwise it will not be mapped to any of the properties of the object and you will loose the primary key reference.

    您应该始终在bean中具有id字段,否则它将不会被映射到对象的任何属性,并且您将失去主键引用。

Now let’s see how we can easily use Spring Data MongoDB to perform CRUD operations on MongoDB database.

现在,让我们看看如何轻松地使用Spring Data MongoDB在MongoDB数据库上执行CRUD操作。

SpringDataMongoDBMain.java

SpringDataMongoDBMain.java

package com.journaldev.spring.mongodb.main;

import java.net.UnknownHostException;

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

import com.journaldev.spring.mongodb.model.Person;
import com.mongodb.MongoClient;

public class SpringDataMongoDBMain {

	public static final String DB_NAME = "journaldev";
	public static final String PERSON_COLLECTION = "Person";
	public static final String MONGO_HOST = "localhost";
	public static final int MONGO_PORT = 27017;

	public static void main(String[] args) {
		try {
			MongoClient mongo = new MongoClient(
					MONGO_HOST, MONGO_PORT);
			MongoOperations mongoOps = new MongoTemplate(mongo, DB_NAME);
			Person p = new Person("113", "PankajKr", "Bangalore, India");
			mongoOps.insert(p, PERSON_COLLECTION);

			Person p1 = mongoOps.findOne(
					new Query(Criteria.where("name").is("PankajKr")),
					Person.class, PERSON_COLLECTION);

			System.out.println(p1);
			
			mongoOps.dropCollection(PERSON_COLLECTION);
			mongo.close();
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}

}

Now when I run above Spring Data MongoDB example program, it generates following output.

现在,当我在Spring Data MongoDB示例程序上方运行时,它将生成以下输出。

02:02:14.785 [main] DEBUG o.s.d.m.c.i.MongoPersistentEntityIndexCreator - Analyzing class class com.journaldev.spring.mongodb.model.Person for index information.
02:02:14.794 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - Inserting DBObject containing fields: [_class, _id, name, address] in collection: Person
02:02:14.798 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Getting Mongo Database name=[journaldev]
02:02:14.824 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - findOne using query: { "name" : "PankajKr"} fields: null for class: class com.journaldev.spring.mongodb.model.Person in collection: Person
02:02:14.826 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Getting Mongo Database name=[journaldev]
02:02:14.826 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - findOne using query: { "name" : "PankajKr"} in db.collection: journaldev.Person
113::PankajKr::Bangalore, India
02:02:14.833 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Getting Mongo Database name=[journaldev]
02:02:14.835 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - Dropped collection [journaldev.Person]

We can conclude following points for Spring Data MongoDB from our learning till now.

从我们的学习到现在,我们可以总结出Spring Data MongoDB的以下几点。

  1. Spring Data MongoDB provides wrapper over the MongoDB java driver, internally it’s using MongoDB java driver to perform database operations.

    Spring Data MongoDB提供了对MongoDB Java驱动程序的包装,内部使用MongoDB Java驱动程序执行数据库操作。
  2. MongoOperations declares a lot of methods for different operations and most of the time, they are sufficient for us. MongoTemplate is the implementation class and it requires Mongo or MongoClient (for newer MongoDB java driver versions) or MongoDbFactory to initialize it. We also need to provide the database name which will be used.

    MongoOperations声明了许多用于不同操作的方法,大多数情况下,它们对我们来说已经足够了。 MongoTemplate是实现类,它需要MongoMongoClient (对于更新的MongoDB Java驱动程序版本)或MongoDbFactory进行初始化。 我们还需要提供将要使用的数据库名称。
  3. If database is password protected, we can use org.springframework.data.authentication.UserCredentials to pass the authentication username and password details.

    如果数据库受密码保护,则可以使用org.springframework.data.authentication.UserCredentials传递身份验证用户名和密码详细信息。
  4. org.springframework.data.mongodb.core.query.Query and org.springframework.data.mongodb.core.query.Criteria classes are used to define the query used to find particular record or records.

    org.springframework.data.mongodb.core.query.Queryorg.springframework.data.mongodb.core.query.Criteria类用于定义用于查找特定记录的查询。
  5. The major benefit of Spring Data MongoDB is that we don’t need to worry about the conversion of java bean to Mongo DBObject and vice versa, as we saw in MongoDB Java Example.

    Spring Data MongoDB的主要好处是,我们无需担心将Java Bean转换为Mongo DBObject,反之亦然,就像在MongoDB Java Example中看到的那样。

Now let’s move forward to use Spring Data MongoDB in Spring environment. It’s very simple and mostly requires configuration related code that we can do through XML, annotations or through java config. However I will use XML based configuration for Spring Data MongoDB example.

现在,让我们继续在Spring环境中使用Spring Data MongoDB。 这非常简单,并且主要需要与配置相关的代码,我们可以通过XML,注释或java config来执行这些代码。 但是,对于Spring Data MongoDB示例,我将使用基于XML的配置。

Here is my final pom.xml with Spring Framework and Spring Data MongoDB dependencies.

这是我最后带有Spring Framework和Spring Data MongoDB依赖项的pom.xml。


  4.0.0
  org.springframework.samples
  SpringMongo
  0.0.1-SNAPSHOT
  
  

		
		1.6
		UTF-8
		UTF-8

		
		4.0.3.RELEASE
		1.5.2.RELEASE

		
		1.0.13
		1.7.5

	
	
	
		
		
			org.springframework
			spring-context
			${spring-framework.version}
		
		
			org.springframework
			spring-tx
			${spring-framework.version}
		
		
		
    		org.springframework.data
    		spring-data-mongodb
    		${spring-data-mongodb.version}
  		
  
		
		
			org.slf4j
			slf4j-api
			${slf4j.version}
			compile
		
		
			ch.qos.logback
			logback-classic
			${logback.version}
			runtime
		

		

Spring Data MongoDB DAO类 (Spring Data MongoDB DAO Classes)

We will use DAO pattern for exposing different operations that can be performed on Person object.

我们将使用DAO模式公开可以对Person对象执行的不同操作。

PersonDAO.java

PersonDAO.java

package com.journaldev.spring.mongodb.dao;

import com.journaldev.spring.mongodb.model.Person;

public interface PersonDAO {

	public void create(Person p);
	
	public Person readById(String id);
	
	public void update(Person p);
	
	public int deleteById(String id);
}

Below is the MongoDB specific implementation class.

下面是MongoDB特定的实现类。

PersonDAOImpl.java

PersonDAOImpl.java

package com.journaldev.spring.mongodb.dao;

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

import com.journaldev.spring.mongodb.model.Person;
import com.mongodb.WriteResult;

public class PersonDAOImpl implements PersonDAO {

	private MongoOperations mongoOps;
	private static final String PERSON_COLLECTION = "Person";
	
	public PersonDAOImpl(MongoOperations mongoOps){
		this.mongoOps=mongoOps;
	}
	
	@Override
	public void create(Person p) {
		this.mongoOps.insert(p, PERSON_COLLECTION);
	}

	@Override
	public Person readById(String id) {
		Query query = new Query(Criteria.where("_id").is(id));
		return this.mongoOps.findOne(query, Person.class, PERSON_COLLECTION);
	}

	@Override
	public void update(Person p) {
		this.mongoOps.save(p, PERSON_COLLECTION);
	}

	@Override
	public int deleteById(String id) {
		Query query = new Query(Criteria.where("_id").is(id));
		WriteResult result = this.mongoOps.remove(query, Person.class, PERSON_COLLECTION);
		return result.getN();
	}

}

The code is pretty straight forward, so I won’t explain about them in detail.

该代码非常简单明了,因此我将不对其进行详细说明。

Spring Data MongoDB Bean配置文件 (Spring Data MongoDB Bean Configuration File)

As always, the most important part of this application will be the spring bean configuration file. We will inject dependencies into different beans and define them.

与往常一样,该应用程序最重要的部分将是spring bean配置文件。 我们将依赖项注入到不同的bean中并进行定义。

Here is our final spring bean configuration file.

这是我们最终的spring bean配置文件。

spring.xml

spring.xml








	



	

The important configurations that should be present are – Spring Data MongoDB schema and Mongo instance for MongoDB connection. I have defined MongoDbFactory instance for my convenience, we could also define MongoTemplate bean like below,

应该存在的重要配置是–用于MongoDB连接的Spring Data MongoDB模式和Mongo实例。 为了方便起见,我已经定义了MongoDbFactory实例,我们也可以如下定义MongoTemplate bean,


	
	

Spring Data MongoDB测试程序 (Spring Data MongoDB Test Program)

Finally, let’s write a simple test program and run some CRUD operations on MongoDB database.

最后,让我们编写一个简单的测试程序,并在MongoDB数据库上运行一些CRUD操作。

SpringMongoDBXMLMain.java

SpringMongoDBXMLMain.java

package com.journaldev.spring.mongodb.main;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.journaldev.spring.mongodb.dao.PersonDAO;
import com.journaldev.spring.mongodb.model.Person;

public class SpringMongoDBXMLMain {

	public static void main(String[] args) {
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
		
		PersonDAO personDAO = ctx.getBean("personDAO", PersonDAO.class);
		
		Person p = new Person(null, "PankajKr", "Bangalore, India");
		
		//create
		personDAO.create(p);
		System.out.println("Generated ID="+p.getId());
		
		//read
		Person p1 = personDAO.readById(p.getId());
		System.out.println("Retrieved Person="+p1);
		
		//update
		p1.setName("David");p1.setAddress("SFO, USA");
		personDAO.update(p1);
		Person temp = personDAO.readById(p1.getId());
		System.out.println("Retrieved Person after update="+temp);
		
		//delete
		int count = personDAO.deleteById(p1.getId());
		System.out.println("Number of records deleted="+count);
		
		ctx.close();

	}

}

Now when I run above application, it generates following output.

现在,当我在应用程序上方运行时,它将生成以下输出。

02:27:34.509 [main] DEBUG o.s.d.m.c.i.MongoPersistentEntityIndexCreator - Analyzing class class com.journaldev.spring.mongodb.model.Person for index information.
02:27:34.516 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - Inserting DBObject containing fields: [_class, _id, name, address] in collection: Person
02:27:34.520 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Getting Mongo Database name=[journaldev]
Generated ID=53f50bbe0364b65dbc0c4753
02:27:34.532 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - findOne using query: { "_id" : "53f50bbe0364b65dbc0c4753"} fields: null for class: class com.journaldev.spring.mongodb.model.Person in collection: Person
02:27:34.533 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Getting Mongo Database name=[journaldev]
02:27:34.535 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - findOne using query: { "_id" : { "$oid" : "53f50bbe0364b65dbc0c4753"}} in db.collection: journaldev.Person
Retrieved Person=53f50bbe0364b65dbc0c4753::PankajKr::Bangalore, India
02:27:34.543 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - Saving DBObject containing fields: [_class, _id, name, address]
02:27:34.543 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Getting Mongo Database name=[journaldev]
02:27:34.545 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - findOne using query: { "_id" : "53f50bbe0364b65dbc0c4753"} fields: null for class: class com.journaldev.spring.mongodb.model.Person in collection: Person
02:27:34.545 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Getting Mongo Database name=[journaldev]
02:27:34.546 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - findOne using query: { "_id" : { "$oid" : "53f50bbe0364b65dbc0c4753"}} in db.collection: journaldev.Person
Retrieved Person after update=53f50bbe0364b65dbc0c4753::David::SFO, USA
02:27:34.549 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Getting Mongo Database name=[journaldev]
02:27:34.550 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - Remove using query: { "_id" : { "$oid" : "53f50bbe0364b65dbc0c4753"}} in collection: Person.
Number of records deleted=1
02:27:34.553 [main] INFO  o.s.c.s.ClassPathXmlApplicationContext - Closing org.springframework.context.support.ClassPathXmlApplicationContext@7a187814: startup date [Thu Aug 21 02:27:33 GMT+05:30 2014]; root of context hierarchy
02:27:34.553 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
02:27:34.553 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3f64b09c: defining beans [mongo,org.springframework.beans.factory.config.CustomEditorConfigurer#0,org.springframework.beans.factory.config.CustomEditorConfigurer#1,org.springframework.beans.factory.config.CustomEditorConfigurer#2,mongoDbFactory,mongoTemplate,personDAO]; root of factory hierarchy
02:27:34.554 [main] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name 'mongoDbFactory'
02:27:34.554 [main] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name 'mongo'

Notice that when Spring context is closed, it’s taking care of closing the MongoDB connections too, so we don’t need to worry about that.

请注意,当Spring上下文关闭时,它也将关闭MongoDB连接,因此我们不必担心。

Also I am providing MongoDB Collection name in each of the queries, we can skip that if the collection name confirms to java naming convention. For example, for “Person” and “PersonAddress” objects default collection name used by Spring MongoDB would be “person” and “personAddress” respectively.

另外,我在每个查询中都提供了MongoDB集合名称,如果集合名称符合Java命名约定,我们可以跳过它。 例如,对于“ Person”和“ PersonAddress”对象,Spring MongoDB使用的默认集合名称分别为“ person”和“ personAddress”。

We can also use org.springframework.data.mongodb.core.mapping.Document annotation with Model class to define the collection name to be used for saving the document.

我们还可以将org.springframework.data.mongodb.core.mapping.Document注释与Model类一起使用,以定义用于保存文档的集合名称。

基于Spring Data MongoDB注释的配置 (Spring Data MongoDB Annotation Based Configuration)

If you want to use annotation based configuration, below Configuration class can be used for reference.

如果要使用基于注释的配置,可以使用下面的Configuration类作为参考。

SpringMongoDBConfiguration.java

SpringMongoDBConfiguration.java

package com.journaldev.spring.mongodb.config;
 
import org.springframework.context.annotation.Bean;
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 com.mongodb.MongoClient;
 
@Configuration
public class SpringMongoDBConfiguration {
 
	public @Bean MongoDbFactory getMongoDbFactory() throws Exception {
		return new SimpleMongoDbFactory(new MongoClient("localhost",27017), "journaldev");
	}

	public @Bean MongoTemplate getMongoTemplate() throws Exception {
		MongoTemplate mongoTemplate = new MongoTemplate(getMongoDbFactory());
		return mongoTemplate;
	}
}

We would need other configurations too to inject MongoTemplate bean into our DAO implementation class, I am leaving that part to you.

我们还需要其他配置才能将MongoTemplate bean注入我们的DAO实现类中,这部分留给您。

对MongoDB连接选项使用MongoOptions (Using MongoOptions for MongoDB Connection Options)

We can use MongoOptions to define MongoDB options in spring bean configuration file like below. There are some other configuration options too, that you can check for optimizing your connections.

我们可以使用MongoOptions在Spring bean配置文件中定义MongoDB选项,如下所示。 还有其他一些配置选项,您可以检查这些选项以优化连接。


    
  

Spring Data MongoDB示例摘要 (Spring Data MongoDB Example Summary)

I hope this tutorial was good enough to get you started with Spring Data MongoDB, it’s not feasible to cover everything. You should look more into Query, Criteria and MongoTemplate methods to learn more. You can download the final project from below link.

我希望本教程足以让您开始使用Spring Data MongoDB,但涵盖所有内容并不可行。 您应该更多地研究Query,Criteria和MongoTemplate方法以了解更多信息。 您可以从下面的链接下载最终项目。

Download Spring Data MongoDB Project 下载Spring Data MongoDB项目

翻译自: https://www.journaldev.com/4144/spring-data-mongodb-example

你可能感兴趣的:(数据库,java,spring,mysql,spring,boot)