SpringBoot 集成MongoDB

1、项目结构

pom.xml 文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.zzg</groupId>
		<artifactId>mysql-boot</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>mysql-boot-mongodb</artifactId>
	<dependencies>
		<!--依赖mongodb -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-mongodb</artifactId>
			<version>2.1.2.RELEASE</version>
		</dependency>
	</dependencies>
</project>

mongodb封装 核心代码:

package com.zzg.mongodb.config.entity;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@Configuration
@ConfigurationProperties(prefix = "com.zzg.mongodb") 
@PropertySource("classpath:mongodb.properties")
public class MongODBConfigEntity {
	private String host;
	private String port;
	private String database;
	private String username;
	private String password;
	private String socketTimeout;
	private String connectTimeout;
	private String connectionsPerHost;
	
	// set 和 get 方法
	public String getHost() {
		return host;
	}
	public void setHost(String host) {
		this.host = host;
	}
	public String getPort() {
		return port;
	}
	public void setPort(String port) {
		this.port = port;
	}
	public String getDatabase() {
		return database;
	}
	public void setDatabase(String database) {
		this.database = database;
	}
	public String getSocketTimeout() {
		return socketTimeout;
	}
	public void setSocketTimeout(String socketTimeout) {
		this.socketTimeout = socketTimeout;
	}
	public String getConnectTimeout() {
		return connectTimeout;
	}
	public void setConnectTimeout(String connectTimeout) {
		this.connectTimeout = connectTimeout;
	}
	public String getConnectionsPerHost() {
		return connectionsPerHost;
	}
	public void setConnectionsPerHost(String connectionsPerHost) {
		this.connectionsPerHost = connectionsPerHost;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	// 自定义方法
	public String getURI(){
		// 标准个数 =  mongodb://userName:passWord@127.0.0.1:27017/DBname
		StringBuilder builder = new StringBuilder();
		builder.append("mongodb://").append(this.username).append(":").append(this.password).append("@")
			.append(this.host).append(":").append(this.port).append("/").append(this.database);
		return builder.toString().trim();
	}
	
	
	


}
package com.zzg.mongodb.config;

import org.springframework.beans.factory.annotation.Autowired;
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.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.zzg.mongodb.config.entity.MongODBConfigEntity;

@Configuration
public class MongODBConfig {
	@Autowired
	private MongODBConfigEntity entity;

	// 获取MongoDbFactory 对象
	@Bean
	public MongoDbFactory getMongDbFactory() {
		MongoClientOptions.Builder builder = MongoClientOptions.builder()
				.socketTimeout(Integer.valueOf(entity.getSocketTimeout().trim()))
				.connectTimeout(Integer.valueOf(entity.getConnectTimeout().trim()))
				.connectionsPerHost(Integer.valueOf(entity.getConnectionsPerHost().trim()));
		MongoClientURI mongoClientURI = new MongoClientURI(entity.getURI(), builder);
		return new SimpleMongoDbFactory(mongoClientURI);
	}
	
	// 获取MongoTemplate 对象
	@Bean
	public MongoTemplate getMongoTemplate(){
		return new MongoTemplate(getMongDbFactory());
	}

}
package com.zzg.mongodb.common.inter;

import java.util.List;

import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

/**
 * 
 * @ClassName:  BaseMongoDao   
 * @Description: 基础公共接口定义  
 * @author: ** -zzg
 * @date:   2019年4月9日 下午4:45:38   
 *   
 * @param <T>  
 * @Copyright: 2019 www.digipower.cn 
 * 注意:本内容仅限于****技开发有限公司内部使用,禁止用于其他的商业目的
 */
public interface BaseMongoDao<T> {
	
	 public List<T> find(Query query);
	 
	 public T findOne(Query query);
	 
	 public void update(Query query, Update update);
	 
	 public T save(T entity);
	 
	 public T findById(String id);
	 
	 public T findById(String id, String collectionName);
	 
	 public long count(Query query);
	 
	 public void remove(Query query);
	 
	 

}
package com.zzg.mongodb.common;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import com.zzg.mongodb.common.inter.BaseMongoDao;
import com.zzg.mongodb.reflect.ReflectionUtils;

/**
 * 
 * @ClassName:  BaseMongoDaoImpl   
 * @Description: mongodb 抽象类组件  
 * @author: *** -zzg
 * @date:   2019年4月9日 下午4:51:59   
 *   
 * @param <T>  
 * @Copyright: 2019 www.digipower.cn 
 * 注意:本内容仅限于****科技开发有限公司内部使用,禁止用于其他的商业目的
 */

@Component
public abstract class BaseMongoDaoImpl<T> implements BaseMongoDao<T> {
//	@Autowired
//	private MongoTemplate template;
	
	/**
     * spring mongodb 集成操作类
     */
    protected MongoTemplate template;
    
    /**
     * 注入mongodbTemplate
     *
     * @param mongoTemplate
     */
    protected abstract void setMongoTemplate(MongoTemplate template);
    

	@Override
	public List<T> find(Query query) {
		// TODO Auto-generated method stub
		return template.find(query, this.getEntityClass());
	}

	@Override
	public T findOne(Query query) {
		// TODO Auto-generated method stub
		return template.findOne(query, this.getEntityClass());
	}

	@Override
	public void update(Query query, Update update) {
		// TODO Auto-generated method stub
		template.findAndModify(query, update, this.getEntityClass());
	}

	@Override
	public T save(T entity) {
		// TODO Auto-generated method stub
		template.insert(entity);
		return entity;
	}

	@Override
	public T findById(String id) {
		// TODO Auto-generated method stub
		return template.findById(id, this.getEntityClass());
	}

	@Override
	public T findById(String id, String collectionName) {
		// TODO Auto-generated method stub
		return template.findById(id, this.getEntityClass(), collectionName);
	}

	@Override
	public long count(Query query) {
		// TODO Auto-generated method stub
		return template.count(query, this.getEntityClass());
	}

	@Override
	public void remove(Query query) {
		// TODO Auto-generated method stub
		template.remove(query, this.getEntityClass());
	}
	
	/**
     * 获取需要操作的实体类class
     *
     * @return
     */
    private Class<T> getEntityClass() {
        return ReflectionUtils.getSuperClassGenricType(getClass());
    }
}
package com.zzg.mongodb.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
/**
 * 
 * @ClassName:  ReflectionUtils   
 * @Description: 反射工具类
 * @author: 世纪伟图 -zzg
 * @date:   2019年4月9日 下午4:55:34   
 *     
 * @Copyright: 2019 www.digipower.cn 
 * 注意:本内容仅限于深圳市世纪伟图科技开发有限公司内部使用,禁止用于其他的商业目的
 */


public class ReflectionUtils {
	// 错误日志记录
	private final static Logger logger = LoggerFactory.getLogger(ReflectionUtils.class);
	
	/**
     * 调用Getter方法.
     */
    public static Object invokeGetterMethod(Object obj, String propertyName) {
        String getterMethodName = "get" + StringUtils.capitalize(propertyName);
        return invokeMethod(obj, getterMethodName, new Class[] {}, new Object[] {});
    }

    /**
     * 调用Setter方法.使用value的Class来查找Setter方法.
     */
    public static void invokeSetterMethod(Object obj, String propertyName, Object value) {
        invokeSetterMethod(obj, propertyName, value, null);
    }

    /**
     * 调用Setter方法.
     *
     * @param propertyType 用于查找Setter方法,为空时使用value的Class替代.
     */
    public static void invokeSetterMethod(Object obj, String propertyName, Object value,
        Class<?> propertyType) {
        Class<?> type = propertyType != null ? propertyType : value.getClass();
        String setterMethodName = "set" + StringUtils.capitalize(propertyName);
        invokeMethod(obj, setterMethodName, new Class[] {type}, new Object[] {value});
    }

    /**
     * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
     */
    public static Object getFieldValue(final Object obj, final String fieldName) {
        Field field = getAccessibleField(obj, fieldName);

        if (field == null) {
            throw new IllegalArgumentException(
                "Could not find field [" + fieldName + "] on target [" + obj + "]");
        }

        Object result = null;
        try {
            result = field.get(obj);
        } catch (IllegalAccessException e) {
            logger.error("不可能抛出的异常" + e.getMessage());
        }
        return result;
    }

    /**
     * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
     */
    public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
        Field field = getAccessibleField(obj, fieldName);

        if (field == null) {
            throw new IllegalArgumentException(
                "Could not find field [" + fieldName + "] on target [" + obj + "]");
        }

        try {
            field.set(obj, value);
        } catch (IllegalAccessException e) {
            logger.error("不可能抛出的异常" + e.getMessage());
        }
    }

    /**
     * 循环向上转型, 获取对象的DeclaredField,   并强制设置为可访问.
     * <p>
     * 如向上转型到Object仍无法找到, 返回null.
     */
    public static Field getAccessibleField(final Object obj, final String fieldName) {
        Assert.notNull(obj, "object不能为空");
        Assert.hasText(fieldName, "fieldName");
        for (Class<?> superClass = obj.getClass();
             superClass != Object.class; superClass = superClass.getSuperclass()) {
            try {
                Field field = superClass.getDeclaredField(fieldName);
                field.setAccessible(true);
                return field;
            } catch (NoSuchFieldException e) {//NOSONAR
                // Field不在当前类定义,继续向上转型
            }
        }
        return null;
    }

    /**
     * 直接调用对象方法, 无视private/protected修饰符.
     * 用于一次性调用的情况.
     */
    public static Object invokeMethod(final Object obj, final String methodName,
        final Class<?>[] parameterTypes, final Object[] args) {
        Method method = getAccessibleMethod(obj, methodName, parameterTypes);
        if (method == null) {
            throw new IllegalArgumentException(
                "Could not find method [" + methodName + "] on target [" + obj + "]");
        }

        try {
            return method.invoke(obj, args);
        } catch (Exception e) {
            throw convertReflectionExceptionToUnchecked(e);
        }
    }

    /**
     * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
     * 如向上转型到Object仍无法找到, 返回null.
     * <p>
     * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
     */
    public static Method getAccessibleMethod(final Object obj, final String methodName,
        final Class<?>... parameterTypes) {
        Assert.notNull(obj, "object不能为空");

        for (Class<?> superClass = obj.getClass();
             superClass != Object.class; superClass = superClass.getSuperclass()) {
            try {
                Method method = superClass.getDeclaredMethod(methodName, parameterTypes);

                method.setAccessible(true);

                return method;

            } catch (NoSuchMethodException e) {//NOSONAR
                // Method不在当前类定义,继续向上转型
            }
        }
        return null;
    }

    /**
     * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
     * 如无法找到, 返回Object.class.
     * eg.
     * public UserDao extends HibernateDao<User>
     *
     * @param clazz The class to introspect
     * @return the first generic declaration, or Object.class if cannot be determined
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static <T> Class<T> getSuperClassGenricType(final Class clazz) {
        return getSuperClassGenricType(clazz, 0);
    }

    /**
     * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
     * 如无法找到, 返回Object.class.
     * <p>
     * 如public UserDao extends HibernateDao<User,Long>
     *
     * @param clazz clazz The class to introspect
     * @param index the Index of the generic ddeclaration,start from 0.
     * @return the index generic declaration, or Object.class if cannot be determined
     */
    @SuppressWarnings("rawtypes")
    public static Class getSuperClassGenricType(final Class clazz, final int index) {

        Type genType = clazz.getGenericSuperclass();

        if (!(genType instanceof ParameterizedType)) {
            logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
            return Object.class;
        }

        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

        if (index >= params.length || index < 0) {
            logger.warn(
                "Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
                    + params.length);
            return Object.class;
        }
        if (!(params[index] instanceof Class)) {
            logger.warn(clazz.getSimpleName()
                + " not set the actual class on superclass generic parameter");
            return Object.class;
        }

        return (Class) params[index];
    }

    /**
     * 将反射时的checked exception转换为unchecked exception.
     */
    public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
        if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
            || e instanceof NoSuchMethodException) {
            return new IllegalArgumentException("Reflection Exception.", e);
        } else if (e instanceof InvocationTargetException) {
            return new RuntimeException("Reflection Exception.",
                ((InvocationTargetException) e).getTargetException());
        } else if (e instanceof RuntimeException) {
            return (RuntimeException) e;
        }
        return new RuntimeException("Unexpected Checked Exception.", e);
    }

}

第二步:功能测试

mongodb.properties

com.zzg.mongodb.host=127.0.0.1
com.zzg.mongodb.port=27017
com.zzg.mongodb.database=admin
com.zzg.mongodb.username=root
com.zzg.mongodb.password=123456
com.zzg.mongodb.socketTimeout=3000
com.zzg.mongodb.connectTimeout=3000
com.zzg.mongodb.connectionsPerHost=20
package com.zzg.mongodb.repository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;
import com.zzg.entity.Book;
import com.zzg.mongodb.common.BaseMongoDaoImpl;

@Repository
public class BookRepository extends BaseMongoDaoImpl<Book>{
	@Autowired
	@Override
	protected void setMongoTemplate(MongoTemplate template) {
		// TODO Auto-generated method stub
		this.template = template;
	}
}
package com.zzg.controller;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zzg.api.BookService;
import com.zzg.entity.Book;
import com.zzg.mongodb.repository.BookRepository;

@Controller
@RequestMapping("/mongodb")
public class MongodbControlller {
	
	// 引入日志
	private final static Logger logger = LoggerFactory.getLogger(MongodbControlller.class);
	
	@Autowired
	private BookService service;
	@Autowired
	private BookRepository repository;

	
	@RequestMapping(value = "/inser", method = { RequestMethod.GET })
	@ResponseBody
	public void getBooks() {
		List<Book> list = service.getBooks();
		if(list != null && list.size() > 0){
			list.stream().forEach(item ->{
				repository.save(item);
				logger.error("mongodb 数据插入成功");
			});
		}
		
		
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值