the study to MongoDb from spring

一,mongodbtemplate 

  first of all, mongodb helper of spring is MongoTemplate(MongoOperations),spring provides operation API and mapping between MongoDB documents and domain classes 

  if you want use the API,you need to instance a mongodbfactory or mongodbclient, both are useful,because the constructor of MongoOperations needs a mongodbfactory or mongodbclient or connectionString,as shown in the following example:

    public MongoTemplate(com.mongodb.client.MongoClient mongoClient, String databaseName) {
        this((MongoDbFactory)(new SimpleMongoClientDbFactory(mongoClient, databaseName)), (MongoConverter)((MongoConverter)null));
    }

    public MongoTemplate(MongoDbFactory mongoDbFactory) {
        this(mongoDbFactory, (MongoConverter)null);
    }

  @Bean
    public MongoOperations getMongoTemplate(){
        return new MongoTemplate(new SimpleMongoClientDbFactory(properties.getProperty("connectionString")));
    }

  yang:
    mongo:
      connectionString: mongodb://name:password@host:port/dbname

  we get a template now, and the template is thread safe and can be reused across multiple instances. it is important sometimes.

二, attributes 

  the mapping is done by delegating to an implementation of the MongoConverter interface,spring provides a default MongoConverter named MappingMongoConverter,also you can own a yourself MongoConverter ,

  {  

  in addition,template is friendly to develpers, because it is designed by mongodb driver api,and it is more useful,because MongoOperations has fluent APIs for QueryCriteria, and Update operations instead of populating a Document to specify the parameters for those operations.

   }

  the default mapping provides two ways to complate the mapping function, first you can use additional metadata to specify the mapping of objects to documents, a example is use mapping annotations ,another way is by conventions . and spring translation of mongodb driver exception into spring‘s exception.

public MongoTemplate(MongoDbFactory mongoDbFactory, @Nullable MongoConverter mongoConverter) {
     this.writeConcernResolver = DefaultWriteConcernResolver.INSTANCE;//write operation enum, default value is insert
        this.writeResultChecking = WriteResultChecking.NONE;
        this.sessionSynchronization = SessionSynchronization.ON_ACTUAL_TRANSACTION;
        Assert.notNull(mongoDbFactory, "MongoDbFactory must not be null!");
        this.mongoDbFactory = mongoDbFactory;
        this.exceptionTranslator = mongoDbFactory.getExceptionTranslator();
        this.mongoConverter = mongoConverter == null ? getDefaultMongoConverter(mongoDbFactory) : mongoConverter;
        this.queryMapper = new QueryMapper(this.mongoConverter);
        this.updateMapper = new UpdateMapper(this.mongoConverter);
        this.schemaMapper = new MongoJsonSchemaMapper(this.mongoConverter);
        this.projectionFactory = new SpelAwareProxyProjectionFactory();
        this.operations = new EntityOperations(this.mongoConverter.getMappingContext());
        this.propertyOperations = new PropertyOperations(this.mongoConverter.getMappingContext());
        this.mappingContext = this.mongoConverter.getMappingContext();
        if (this.mappingContext instanceof MongoMappingContext) {
            MongoMappingContext mappingContext = (MongoMappingContext)this.mappingContext;
            if (mappingContext.isAutoIndexCreation()) {
                this.indexCreator = new MongoPersistentEntityIndexCreator(mappingContext, this);
                this.eventPublisher = new MongoMappingEventPublisher(this.indexCreator);
                mappingContext.setApplicationEventPublisher(this.eventPublisher);
            }
        }
    }

   spring provides WriteResultChecking policy. in anther word,  you can throw exception or do nothing by modify WriteResultChecking attribute from mongodbtemplate instance when you do some opertains by mongodbtemplate. and the WriteResultChecking class is a enum class,the dafault value of WriteResultChecking  is NONE, like this :

  WriteConcern attribute will be used to the param of mongodb drive.it have some attribute ,such as wTimeoutMS,fsync,journal,and so on.if it not be set by mongodbclient,then it will be set by mongodb driver's attribute.it's a param to tell mongodb driver about the attributes.

  WriteConcernResolver can resolve MongoAction object, and get the three attributes Customized you writed.  the MongoAction  Object include collection name,pojo class,the converted Document,the operation(insert,update,remove,save),and you can make your Customized adjument.like this:

 1 public interface WriteConcernResolver {
 2   WriteConcern resolve(MongoAction action);
 3 }
 4 
 5 private class MyAppWriteConcernResolver implements WriteConcernResolver {
 6 
 7   public WriteConcern resolve(MongoAction action) {
 8     if (action.getEntityClass().getSimpleName().contains("Audit")) {
 9       return WriteConcern.NONE;
10     } else if (action.getEntityClass().getSimpleName().contains("Metadata")) {
11       return WriteConcern.JOURNAL_SAFE;
12     }
13     return action.getDefaultWriteConcern();
14   }
15 }

六,CURD Documents

  mongodbtemplate provides operation to operate pojo,and map those pojo to documents sttored in mongodb server.

   create a pojo ,and do operations

 1 package org.spring.example;
 2 
 3 import static org.springframework.data.mongodb.core.query.Criteria.where;
 4 import static org.springframework.data.mongodb.core.query.Update.update;
 5 import static org.springframework.data.mongodb.core.query.Query.query;
 6 
 7 import java.util.List;
 8 
 9 import org.apache.commons.logging.Log;
10 import org.apache.commons.logging.LogFactory;
11 import org.springframework.data.mongodb.core.MongoOperations;
12 import org.springframework.data.mongodb.core.MongoTemplate;
13 import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
14 
15 import com.mongodb.client.MongoClients;
16 
17 public class MongoApp {
18 
19   private static final Log log = LogFactory.getLog(MongoApp.class);
20 
21   public static void main(String[] args) {
22 
23     MongoOperations mongoOps = new MongoTemplate(new SimpleMongoClientDbFactory(MongoClients.create(), "database"));
24 
25     Person p = new Person("Joe", 34);
26 
27     // Insert is used to initially store the object into the database.
28     mongoOps.insert(p);
29     log.info("Insert: " + p);
30 
31     // Find
32     p = mongoOps.findById(p.getId(), Person.class);
33     log.info("Found: " + p);
34 
35     // Update
36     mongoOps.updateFirst(query(where("name").is("Joe")), update("age", 35), Person.class);
37     p = mongoOps.findOne(query(where("name").is("Joe")), Person.class);
38     log.info("Updated: " + p);
39 
40     // Delete
41     mongoOps.remove(p);
42 
43     // Check that deletion worked
44     List<Person> people =  mongoOps.findAll(Person.class);
45     log.info("Number of people = : " + people.size());
46 
47 
48     mongoOps.dropCollection(Person.class);
49   }
50 }

  mongoConverter convert your pojo to stored document in mongodb server.

七,how deal with my id

   if you use MappingMongoConverter ,use @id,or your pojo have a attribute anmed id. String and int is ok for id. and mongoConverter will  deal with it.

八,type mapping

  MappingMongoConverter will store class infos into server.

1 {
2   "value" : { "_class" : "com.acme.Person" },
3   "_class" : "com.acme.Sample"
4 }

九,insert and save

  MongoTemplate have the follow methods .if you do not set collectionmame, com.yang.person will be store into person cellection.

1 void save (Object objectToSave): Save the object to the default collection.
2 
3 void save (Object objectToSave, String collectionName): Save the object to the specified collection.
4 
5 void insert (Object objectToSave): Insert the object to the default collection.
6 
7 void insert (Object objectToSave, String collectionName): Insert the object to the specified collection.

十,Updating Documents in a Collection

  

   You can use a little "'syntax sugar'" with the Update class.

template.upsert(query(where("ssn").is(1111).and("firstName").is("Joe").and("Fraizer").is("Update")), update("address", addr), Person.class);

   upsert operate will insert if document not exit.

十一,Querying Documents

  1. reating a Query instance from a plain JSON String

  

   2.Querying for documents using the MongoTemplate

  

   All find methods take a Query object as a parameter. This object defines the criteria and options used to perform the query. The criteria are specified by using a Criteria object that has a static factory method named where to instantiate a new Criteria object. We recommend using static imports for org.springframework.data.mongodb.core.query.Criteria.where and Query.query to make the query more readable.

  

原文地址:https://www.cnblogs.com/YsirSun/p/12494096.html