mongodb spring-data 使用

pom文件配置,spring主配置忽略


<dependency>

<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.10.6.RELEASE</version>

</dependency>


创建

mongodb.xml


<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	xmlns:context="http://www.springframework.org/schema/context"
	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/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/util http://www.springframework.org/schema/util/spring-util-4.3.xsd  
    http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.8.xsd  
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">


	<mongo:mongo id="mongo" replica-set="192.168.231.208:27017" >
		<!-- connections-per-host: 每个主机答应的连接数(每个主机的连接池大小),当连接池被用光时,会被阻塞住 max-wait-time: 
			被阻塞线程从连接池获取连接的最长等待时间(ms) connect-timeout:在建立(打开)套接字连接时的超时时间(ms) socket-timeout:套接字超时时间;该值会被传递给 
			Socket.setSoTimeout(int) slave-ok:指明是否答应驱动从次要节点或者奴隶节点读取数据 -->
		<mongo:options connections-per-host="8"
			threads-allowed-to-block-for-connection-multiplier="4"
			connect-timeout="1000" max-wait-time="1500" auto-connect-retry="true"
			socket-keep-alive="true" socket-timeout="1500" slave-ok="true"
			write-number="1" write-timeout="0" write-fsync="true"  />
	</mongo:mongo>


	<!-- 设置使用的数据库 名 -->
	<mongo:db-factory id="mongoDbFactory" dbname="info"  username="test" password="test" mongo-ref="mongo" />
	<!-- mongodb的模板 -->
	 <mongo:template id="mongoTemplate" db-factory-ref="mongoDbFactory" write-concern="NORMAL"/>
<!-- 	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
		<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
	</bean> -->
</beans>

  






创建

MongoUtil


import java.lang.reflect.Field;
import java.util.List;

import javax.annotation.Resource;

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;

@Component
public class MongoUtil<T> {

	@Resource
	private MongoTemplate  mongoTemplate ;
	
	  
    public void save(Object entity) {  
        mongoTemplate.insert(entity);  
     
    }
    public void save(Object entity,String collectionName) {  
        mongoTemplate.insert(entity,collectionName);  
    } 
  
    public T findById(String id) {  
        return mongoTemplate.findById(id, this.getEntityClass());  
    }  
  
    public T findById(String id, String collectionName) {  
        return mongoTemplate.findById(id, this.getEntityClass(), collectionName);  
    }  
  
    public List<T> findAll() {  
        return mongoTemplate.findAll(this.getEntityClass());  
    }  
  
    public List<T> findAll(String collectionName) {  
        return mongoTemplate.findAll(this.getEntityClass(), collectionName);  
    }  
  
    public List<T> find(Query query) {  
        return mongoTemplate.find(query, this.getEntityClass());  
    }  
  
    public T findOne(Query query) {  
        return mongoTemplate.findOne(query, this.getEntityClass());  
    }  
  
    public Page<T> findPage(Page<T> page, Query query) {  
        //如果没有条件 则所有全部  
        query=query==null?new Query(Criteria.where("_id").exists(true)):query;  
        long count = this.count(query);  
        // 总数  
        page.setTotal((int) count);  
        int currentPage = page.getCurrentPage();  
        int pageSize = page.getPageSize();  
        query.skip((currentPage - 1) * pageSize).limit(pageSize);  
        List<T> rows = this.find(query);  
        page.setRows(rows);  
        return page;  
    }  
  
    public long count(Query query) {  
        return mongoTemplate.count(query, this.getEntityClass());  
    }  
  
    public WriteResult update(Query query, Update update) {  
        if (update==null) {  
            return null;  
        }  
        return mongoTemplate.updateMulti(query, update, this.getEntityClass());  
    }  
  
    public T updateOne(Query query, Update update) {  
        if (update==null) {
            return null;  
        }  
        return mongoTemplate.findAndModify(query, update, this.getEntityClass());  
    }  
    
    public WriteResult update(T entity) {  
        Field[] fields = this.getEntityClass().getDeclaredFields();  
        if (fields == null || fields.length <= 0) {  
            return null;  
        }  
        Field idField = null;  
        // 查找ID的field  
        for (Field field : fields) {  
            if (field.getName() != null  
                    && "id".equals(field.getName().toLowerCase())) {  
                idField = field;  
                break;  
            }  
        }  
        if (idField == null) {  
            return null;  
        }  
        idField.setAccessible(true);  
        String id=null;  
        try {  
            id = (String) idField.get(entity);  
        } catch (IllegalArgumentException e) {  
            e.printStackTrace();  
        } catch (IllegalAccessException e) {  
            e.printStackTrace();  
        }  
        if (id == null || "".equals(id.trim()))  
            return null;  
        // 根据ID更新  
        Query query = new Query(Criteria.where("_id").is(id));  
      
        Update update =(Update)entity;  
        if (update == null) {  
            return null;  
        }  
        return mongoTemplate.updateFirst(query, update, getEntityClass());  
    }  
  
    public void remove(Query query) {  
        mongoTemplate.remove(query, this.getEntityClass());  
    }  
    /** 
     * 获得泛型类 
     */  
    private Class<T> getEntityClass() {  
        return ReflectionUtils.getSuperGenericType(getClass());  
    }


}



反射工具类 ReflectionUtils



import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.lang.StringUtils;

public class ReflectionUtils {

	/**
	 * 将反射时的 "检查异常" 转换为 "运行时异常"
	 * @return
	 */
	public static IllegalArgumentException convertToUncheckedException(Exception ex){
		if(ex instanceof IllegalAccessException || ex instanceof IllegalArgumentException
				|| ex instanceof NoSuchMethodException){
			throw new IllegalArgumentException("反射异常", ex);
		}else{
			throw new IllegalArgumentException(ex);
		}
	}
	
	/**
	 * 转换字符串类型到 toType 类型, 或 toType 转为字符串
	 * @param value:  待转换的字符串
	 * @param toType: 提供类型信息的 Class, 可以是基本数据类型的包装类或指定格式日期型
	 * @return
	 */
	public static Object convertValue(Object value, Class<?> toType){
		try {
			DateConverter dc = new DateConverter();
			
			dc.setUseLocaleFormat(true);
			dc.setPatterns(new String[]{"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"});

			ConvertUtils.register(dc, Date.class);
			
			return ConvertUtils.convert(value, toType);
		} catch (Exception e) {
			e.printStackTrace();
			throw convertToUncheckedException(e);
		}
	}

	/**
	 * 提取集合中的对象的属性(通过 getter 方法), 组成 List
	 * @param collection: 来源集合
	 * @param propertyName: 要提取的属性名
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List fetchElementPropertyToList(Collection collection, String propertyName){
		List list = new ArrayList();
		
		try {
			for(Object obj: collection){
				list.add(PropertyUtils.getProperty(obj, propertyName));
			}
		} catch (Exception e) {
			e.printStackTrace();
			convertToUncheckedException(e);
		}
		
		return list;
	}
	
	/**
	 * 提取集合中的对象属性(通过 getter 函数), 组合成由分隔符分隔的字符串
	 * @param collection: 来源集合
	 * @param propertyName: 要提取的属性名
	 * @param seperator: 分隔符
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String fetchElementPropertyToString(Collection collection, String propertyName, 
			String seperator){
		List list = fetchElementPropertyToList(collection, propertyName);
		return StringUtils.join(list, seperator);
	}
	
	/**
	 * 通过反射, 获得定义 Class 时声明的父类的泛型参数的类型
	 * 如: public EmployeeDao extends BaseDao<Employee, String>
	 * @param clazz
	 * @param index
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Class getSuperClassGenricType(Class clazz, int index){
		Type genType = clazz.getGenericSuperclass();
		
		if(!(genType instanceof ParameterizedType)){
			return Object.class;
		}
		
		Type [] params = ((ParameterizedType)genType).getActualTypeArguments();
		
		if(index >= params.length || index < 0){
			return Object.class;
		}
		
		if(!(params[index] instanceof Class)){
			return Object.class;
		}
		
		return (Class) params[index];
	}
	
	/**
	 * 通过反射, 获得 Class 定义中声明的父类的泛型参数类型
	 * 如: public EmployeeDao extends BaseDao<Employee, String>
	 * @param <T>
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static<T> Class<T> getSuperGenericType(Class clazz){
		return getSuperClassGenricType(clazz, 0);
	}
	
	/**
	 * 循环向上转型, 获取对象的 DeclaredMethod
	 * @param object
	 * @param methodName
	 * @param parameterTypes
	 * @return
	 */
	public static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes){
		
		for(Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()){
			try {
				//superClass.getMethod(methodName, parameterTypes);
				return superClass.getDeclaredMethod(methodName, parameterTypes);
			} catch (NoSuchMethodException e) {
				//Method 不在当前类定义, 继续向上转型
			}
			//..
		}
		
		return null;
	}
	
	/**
	 * 使 filed 变为可访问
	 * @param field
	 */
	public static void makeAccessible(Field field){
		if(!Modifier.isPublic(field.getModifiers())){
			field.setAccessible(true);
		}
	}
	
	/**
	 * 循环向上转型, 获取对象的 DeclaredField
	 * @param object
	 * @param filedName
	 * @return
	 */
	public static Field getDeclaredField(Object object, String filedName){
		
		for(Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()){
			try {
				return superClass.getDeclaredField(filedName);
			} catch (NoSuchFieldException e) {
				//Field 不在当前类定义, 继续向上转型
			}
		}
		return null;
	}
	
	/**
	 * 直接调用对象方法, 而忽略修饰符(private, protected)
	 * @param object
	 * @param methodName
	 * @param parameterTypes
	 * @param parameters
	 * @return
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 */
	public static Object invokeMethod(Object object, String methodName, Class<?> [] parameterTypes,
			Object [] parameters) throws InvocationTargetException{
		
		Method method = getDeclaredMethod(object, methodName, parameterTypes);
		
		if(method == null){
			throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]");
		}
		
		method.setAccessible(true);
		
		try {
			return method.invoke(object, parameters);
		} catch(IllegalAccessException e) {

		} 
		
		return null;
	}
	
	/**
	 * 直接设置对象属性值, 忽略 private/protected 修饰符, 也不经过 setter
	 * @param object
	 * @param fieldName
	 * @param value
	 */
	public static void setFieldValue(Object object, String fieldName, Object value){
		Field field = getDeclaredField(object, fieldName);
		
		if (field == null)
			throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
		
		makeAccessible(field);
		
		try {
			field.set(object, value);
		} catch (IllegalAccessException e) {

		}
	}
	
	/**
	 * 直接读取对象的属性值, 忽略 private/protected 修饰符, 也不经过 getter
	 * @param object
	 * @param fieldName
	 * @return
	 */
	public static Object getFieldValue(Object object, String fieldName){
		Field field = getDeclaredField(object, fieldName);
		
		if (field == null)
			throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
		
		makeAccessible(field);
		
		Object result = null;
		
		try {
			result = field.get(object);
		} catch (IllegalAccessException e) {

		}
		
		return result;
	}
}








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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值