spring4 integrates mongodb

1. What is mongodb

MongoDB is a database based on distributed file storage. Written in C++ language. It aims to provide scalable high-performance data storage solutions for WEB applications.
MongoDB is a product between relational databases and non-relational databases. It is the most feature-rich and most like relational databases among non-relational databases. The data structure it supports is very loose and is a bson format similar to json, so it can store more complex data types. The biggest feature of Mongo is that the query language it supports is very powerful. Its syntax is somewhat similar to the object-oriented query language. It can almost realize most functions similar to single-table query in relational databases, and it also supports indexing of data.

(The above is the introduction of Baidu Encyclopedia. For more details, please refer to the official website of mongodb https://www.mongodb.com/ )

 2. Using spring to integrate mongodb in java

 We use the spring-data-mongodb component to integrate mongodb, and the integration process is very simple.

mongodb.properties 

#mongoDB connection configuration
mongo.dbname=myDB
mongo.host = 192.168.1.129
mongo.port=27017
#mongo.username=root
#mongo.password=root
#Maximum number of blocks a thread becomes available

#mongo.writeConcern=SAFE
mongo.connectionsPerHost=8
#Number of thread queues, the result of multiplying the above connectionsPerHost value is the maximum thread queue value
mongo.threadsAllowedToBlockForConnectionMultiplier=4
#Connection timeout (milliseconds)
mongo.connectTimeout=1500
#Maximum waiting time
mongo.maxWaitTime = 1500
#Auto reconnect
mongo.autoConnectRetry=true
#scoket keep it active
mongo.socketKeepAlive= true
#scoket timeout
mongo.socketTimeout=1500

spring-mongodb.xml (note that the version of spring must be above 4)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    xsi:schemaLocation="
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-4.3.xsd
          http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
          http://www.springframework.org/schema/cache
          http://www.springframework.org/schema/cache/spring-cache-4.3.xsd
          http://www.springframework.org/schema/data/mongo
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.10.xsd">
         
       
      <mongo:db-factory id="mongoDbFactory" dbname="${mongo.dbname}" mongo-ref="mongoClient"/>
       
      <!--credentials configuration form is: username:password@default database-->
<!--     <mongo:mongo-client id="mongoClient" host="${mongo.host}" port="${mongo.port}"
                    credentials="${mongo.username}:${mongo.password}@${mongo.dbname}"
          > -->
    <mongo:mongo-client id="mongoClient" host="${mongo.host}" port="${mongo.port}"  >
             <mongo:client-options
                           
                          connections-per-host="${mongo.connectionsPerHost}"
                          threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
                          connect-timeout="${mongo.connectTimeout}"
                          max-wait-time="${mongo.maxWaitTime}"
                          socket-timeout="${mongo.socketTimeout}"
                          />
   </mongo:mongo-client>
 
     
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    </bean>
       
    
     
</beans>

pom.xml

<!--  slf4j jar包 (api)-->
      <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.7</version>
    </dependency>
     <!-- slf4j jar package (implementation) -->
 <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.7</version>
    </dependency>
 
   <!-- spring-data-mongodb 组件  -->
 <dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.10.7.RELEASE</version>
</dependency>

ok, the above integration is complete.

If we need to call mongodb in our business code, we only need @resources to inject the mongoTemplate bean.

3. Simple encapsulation of mongodb operations (CRUD)

MongoBaseDao.java

package com.tingcream.hplusAdmin.business.other.base;
 
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
 
import javax.annotation.Resource;
 
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.MongoTemplate;
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 org.springframework.stereotype.Component;
import com.mongodb.WriteResult;
  
/**
 * Simple encapsulation of mongodb CRUD
 * @author jelly
 */
@Component
public class MongoBaseDo {
     
    @Resource
    private MongoTemplate mongoTemplate;
     
    /**
     * Query by id
     * @param _id primary key id
     * @param entityClass entity class
     * @return T
     * @author jelly
     *
     */
     public <T> T findById( String _id,Class<T> entityClass) {   
            return  mongoTemplate.findById(_id, entityClass);   
     }
     /**
      * Query by id
      * @param _id primary key id
      * @param entityClass entity class
      * @param collectionName collection name
      * @return T
      * @author jelly
      *
      */
     public <T> T findById( String _id,Class<T> entityClass,String collectionName) {   
         return  mongoTemplate.findById(_id, entityClass,collectionName);   
     }
          
      
     /**
      * save an entity object
      * @param t
      * @return T
      * @author jelly
      *
      */
    public  <T> T save(T t){
        mongoTemplate.save(t);
        return t;//Automatic primary key return
    }
    /**
     *
     * @param t
     * @param collectionName
     * @return
     * @return T
     * @author jelly
     *
     */
    public  <T> T save(T t,String collectionName){
        mongoTemplate.save(t,collectionName);
        return t;//Automatic primary key return
    }
     
    /**
     * Query all entity objects
     * @param entityClass
     * @return List<T>
     * @author jelly
     *
     */
    public  <T>  List<T> findAll(Class<T> entityClass){
      return    mongoTemplate.findAll(entityClass);
    }
    /**
     * Query all entity objects
     * @param entityClass
     * @param collectionName
     * @return List<T>
     * @author jelly
     *
     */
    public  <T>  List<T> findAll(Class<T> entityClass,String collectionName){
        return  mongoTemplate.findAll(entityClass,collectionName);
    }
     
    /**
     * delete by id
     * @param _id
     * @param entityClass
     * @return WriteResult
     * @author jelly
     *
     */
    public  <T> WriteResult  deleteById(String _id,Class<T> entityClass){
         Query query =Query.query(Criteria.where("_id").is(new ObjectId(_id)));
          
         return     mongoTemplate.remove(query, entityClass);
           
    }
    /**
     * delete by id
     * @param _id
     * @param entityClass
     * @param collectionName
     * @return WriteResult
     * @author jelly
     *
     */
    public  <T> WriteResult  deleteById(String _id,Class<T> entityClass,String collectionName){
        Query query =Query.query(Criteria.where("_id").is(new ObjectId(_id)));
         
        return     mongoTemplate.remove(query, entityClass,collectionName);
         
    }
      
     
    /**
     * Update an entity object, according to the _id primary key update
     * @param t
     * @throws Exception
     * @return WriteResult
     * @author jelly
     *
     */
    public  <T> WriteResult updateOne(T t) throws Exception{
         
        //where condition, update according to id
         //Query query =Query.query(Criteria.where("_id").is(new ObjectId(_id)));
         Update  update=new Update();
           
           Class<? extends Object> clazz=t.getClass(); //clazz 对象
          
            Field field =   clazz.getDeclaredField("_id");
             
            PropertyDescriptor idDescriptor = new PropertyDescriptor(field.getName(), clazz);
            String _id = (String) idDescriptor.getReadMethod().invoke(t);
             
            Query query =Query.query(Criteria.where("_id").is(new ObjectId(_id)));//查询条件  id
             
          
          BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            
           PropertyDescriptor[] propertyDescriptors= beanInfo.getPropertyDescriptors();//Array of property descriptors
            
         for(int i=0;i<propertyDescriptors.length;i++){
             // property descriptor
             PropertyDescriptor descriptor  = propertyDescriptors[i];
              
              String propertyName = descriptor.getName(); //Get the property name
              
             if(propertyName.equals("class") || propertyName.equals("_id") || propertyName.equals("serialVersionUID")){
                 continue;
             }
                PropertyDescriptor pd = new PropertyDescriptor(propertyName, clazz);
                 Method writeMethod = pd.getWriteMethod ();
                 if(writeMethod==null){
                     continue;
                 }
                 Method readMethod=pd.getReadMethod();
                 String retType= readMethod.getReturnType().getName();
                 if(retType.equals(String.class.getName())){//"java.lang.String"
                      
                    String  value = (String) readMethod.invoke(t);
                      
                     if(StringUtils.isNotEmpty(value)){
                           update.set(propertyName, value);
                     }
                 }else {
                     if(readMethod.invoke(t)!=null){
                          update.set(propertyName, readMethod.invoke(t));  
                     }
                 }
         }
          
         return  mongoTemplate.updateFirst(query, update, clazz);
         
    }
     
    /**
     * Update an entity object, according to the _id primary key update
     * @param t
     * @param collectionName
     * @throws Exception
     * @return WriteResult
     * @author jelly
     *
     */
    public  <T> WriteResult updateOne(T t,String collectionName) throws Exception{
         
        //where condition, update according to id
        //Query query =Query.query(Criteria.where("_id").is(new ObjectId(_id)));
        Update  update=new Update();
         
        Class<? extends Object> clazz=t.getClass(); //clazz 对象
         
        Field field =   clazz.getDeclaredField("_id");
         
        PropertyDescriptor idDescriptor = new PropertyDescriptor(field.getName(), clazz);
        String _id = (String) idDescriptor.getReadMethod().invoke(t);
         
        Query query =Query.query(Criteria.where("_id").is(new ObjectId(_id)));//查询条件  id
         
         
        BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
         
        PropertyDescriptor[] propertyDescriptors= beanInfo.getPropertyDescriptors();//Array of property descriptors
         
        for(int i=0;i<propertyDescriptors.length;i++){
            // property descriptor
            PropertyDescriptor descriptor  = propertyDescriptors[i];
             
            String propertyName = descriptor.getName(); //Get the property name
             
            if(propertyName.equals("class") || propertyName.equals("_id") || propertyName.equals("serialVersionUID")){
                continue;
            }
            PropertyDescriptor pd = new PropertyDescriptor(propertyName, clazz);
            Method writeMethod = pd.getWriteMethod ();
            if(writeMethod==null){
                continue;
            }
            Method readMethod=pd.getReadMethod();
            String retType= readMethod.getReturnType().getName();
            if(retType.equals(String.class.getName())){//"java.lang.String"
                 
                String  value = (String) readMethod.invoke(t);
                if(StringUtils.isNotEmpty(value)){
                    update.set(propertyName, value);    
                }
            }else {
                 if(readMethod.invoke(t)!=null){
                      update.set(propertyName, readMethod.invoke(t));  
                 }
             }
        }
         
        return  mongoTemplate.updateFirst(query, update, clazz,collectionName);
         
    }
     
      
         
}

ok ~~~





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325766905&siteId=291194637