
com.anwen.mongo.toolkit.BsonUtil Maven / Gradle / Ivy
package com.anwen.mongo.toolkit;
import com.anwen.mongo.annotation.collection.CollectionField;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import org.bson.Document;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
/**
* Document转换
*
* @author JiaChaoYang
**/
public class BsonUtil {
/**
* 将Document列换转换JavaList
* @param documents
* @param clazz
* @param
* @return
* @throws IllegalArgumentException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static List toBeans(List documents, Class clazz)
throws IllegalArgumentException, InstantiationException,
IllegalAccessException, InvocationTargetException {
List list = new ArrayList();
for (int i = 0; null != documents && i < documents.size(); i++) {
list.add(toBean(documents.get(i), clazz));
}
return list;
}
/*
* 将Bson 转化为对象
*
* @param:Bson文档
*
* @param:类pojo
*
* @param:返回对象
*/
public static T toBean(Document document, Class clazz) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
T obj = clazz.newInstance();// 声明一个对象
Field[] fields = clazz.getDeclaredFields();// 获取所有属性
Method[] methods = clazz.getMethods();// 获取所有的方法
/*
* 查找所有的属性,并通过属性名和数据库字段名通过相等映射
*/
for (int i = 0; i < fields.length; i++) {
String fieldName = fields[i].getName();
CollectionField column = fields[i].getAnnotation(CollectionField.class);
Object bson = null;
if (null != column && null != column.value()) {
bson = document.get(column.value());
} else if ("id".equals(fieldName)) {
bson = document.get("_id");
} else {
bson = document.get(fieldName);
}
if (null == bson) {
continue;
} else if (bson instanceof Document) {// 如果字段是文档了递归调用
bson = toBean((Document) bson, fields[i].getType());
} else if (bson instanceof MongoCollection) {// 如果字段是文档集了调用colTOList方法
bson = colToList(bson, fields[i]);
}
for (int j = 0; j < methods.length; j++) {// 为对象赋值
String metdName = methods[j].getName();
if (equalFieldAndSet(fieldName, metdName)) {
methods[j].invoke(obj, bson);
break;
}
}
}
return obj;
}
public static List toBsons(List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy