`

沁园下的一缕残云 留——痕 通过java反射实现简单的关于MongoDB的对象关系映射(ORM).

阅读更多

转自:https://www.cnblogs.com/maybo/p/5182439.html

通过阅读MongoDB  3.2.1的官方文档中关于java 编程发现最新的文档并没有实现对对象到Document的映射,所以自己有了利用反射实现简单的关系映射.

  1.定义抽象类:AbstractMongoSession

复制代码
import java.util.List;

import org.bson.Document;
import org.bson.conversions.Bson;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

/*
 * 创建一个会话实现对mongoDB的原子操作
 * 
 * @author:maybo
 * 
 * @date:2016-2-1
 */
public abstract class AbstractMongoSession {
    private MongoDatabase db;
    private Class<?> clazz;
    private MongoCollection<Document> collection;

    public MongoCollection<Document> getCollection() {
        return this.collection;
    }

    public Class<?> getClazz() {
        return clazz;
    }

    public void setDb(MongoDatabase db) {
        this.db = db;
    }

    public MongoDatabase getDb() {
        return db;
    }

    protected MongoCollection<Document> Collection(Class<?> clazz) {
        this.clazz = clazz;
        Table table = (Table) clazz.getAnnotation(Table.class);
        String col = null;
        if (null != table && null != table.name()) {
            col = table.name();
        } else {
            col = clazz.getName();
        }
        this.collection = db.getCollection(col);
        return this.collection;
    }

    /*
     * 保存
     * 
     * @param:实体
     * 
     * @return:void
     */
    public abstract void save(Object obj);

    public abstract void saveMany(List<Object> obj);

    // 删除数据
    public abstract long delete(Object obj) throws Exception;

    public abstract long delete(Bson bson) throws Exception;

    // 删除数据
    public abstract long deleteMany(List<Object> objs);

    public abstract long deleteMany(Bson bson);

    // 修改数据
    public abstract long upate(Bson bson, Object obj);

    public abstract long update(Object obj);

    public abstract long upateMany(Bson bson, Object obj);

    public abstract long upateMany(Bson bson, List<Object> objs);

    public abstract long upateMany(List<Object> objs);

    // 查询数据
    public abstract Object find(Object obj);

    // 获取所有的数据
    public abstract List<Object> finds();

    // 条件查询数据
    public abstract List<Object> query(Bson bson);

    public abstract Object queryOne(Bson bson);

    public abstract List<Object> query(Bson bson, Bson sort);

    public abstract Object queryOne(Bson bson, Bson sort);

    public abstract List<Object> query(Bson bson, Bson sort, int limit);

    public abstract List<Object> query(Bson bson, Bson sort, int limit, int skip);

    public abstract List<Object> query(Bson bson, Bson sort, Bson filter);

    public abstract Object queryOne(Bson bson, Bson sort, Bson Filter);

    public abstract long count();

    public abstract long count(Bson bson);

}
复制代码

2. 实现类MongoSession

复制代码
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.bson.Document;
import org.bson.conversions.Bson;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;

public class MongoSession extends AbstractMongoSession {
    public MongoSession(Class<?> clazz, MongoDatabase db) {
        this.setDb(db);
        this.Collection(clazz);
    }

    /*
     * (non-Javadoc)
     * 
     * @see AbstractMongoSession#save(java.lang.Object)
     */
    @Override
    public void save(Object obj) {
        try {
            this.getCollection().insertOne(BsonUtil.toBson(obj));
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public long delete(Object obj) throws Exception {
        try {
            DeleteResult result = this.getCollection().deleteOne(
                    BsonUtil.toBson(obj));
            long count = result.getDeletedCount();
            return count;
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public void saveMany(List<Object> obj) {
        try {
            this.getCollection().insertMany(BsonUtil.toBsons(obj));
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
    public long delete(Bson bson) throws Exception {
        DeleteResult deleteResult = this.getCollection().deleteOne(bson);
        return deleteResult.getDeletedCount();
    }

    @Override
    public long deleteMany(List<Object> objs) {
        List<Document> documents;
        int count = 0;
        try {
            documents = BsonUtil.toBsons(objs);
            for (int i = 0; null != documents && i < documents.size(); i++) {
                DeleteResult deleteResult = this.getCollection().deleteOne(
                        documents.get(i));
                count += deleteResult.getDeletedCount();
            }
            return count;
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return count;
    }

    @Override
    public long deleteMany(Bson bson) {
        DeleteResult deleteResult = this.getCollection().deleteMany(bson);
        return deleteResult.getDeletedCount();
    }

    @Override
    public long upate(Bson bson, Object obj) {
        try {
            UpdateResult result = this.getCollection().updateOne(bson,
                    new Document("$set", BsonUtil.toBson(obj)));
            return result.getMatchedCount();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public long update(Object obj) {
        Document document;
        try {
            document = BsonUtil.toBson(obj);
            UpdateResult updateResult = this.getCollection().updateOne(
                    Filters.eq("_id", document.get("_id")),
                    new Document("$set", document));
            return updateResult.getMatchedCount();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public long upateMany(Bson bson, Object obj) {
        try {
            UpdateResult updateResult = this.getCollection().updateMany(bson,
                    new Document("$set", BsonUtil.toBson(obj)));
            return updateResult.getMatchedCount();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public long upateMany(Bson bson, List<Object> obj) {
        for (int i = 0; null != obj && i < obj.size(); i++) {
            try {
                UpdateResult result = this.getCollection().updateMany(bson,
                        new Document("$set", BsonUtil.toBson(obj)));
                return result.getMatchedCount();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return 0;
    }

    @Override
    public long upateMany(List<Object> objs) {
        long count = 0;
        for (int i = 0; null != objs && i < objs.size(); i++) {
            try {
                UpdateResult result = this.getCollection().updateMany(
                        Filters.eq("_id",
                                BsonUtil.toBson(objs.get(i)).get("_id")),
                        new Document("$set", BsonUtil.toBson(objs.get(i))));
                count += result.getMatchedCount();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return count;
    }

    @Override
    public Object find(Object obj) {
        try {
            Document document = this.getCollection()
                    .find(Filters.eq("_id", BsonUtil.toBson(obj).get("_id")))
                    .first();
            return BsonUtil.toBean(document, this.getClazz());
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Object> finds() {
        FindIterable<Document> doIterable = this.getCollection().find();
        MongoCursor<Document> cursor = doIterable.iterator();
        List<Object> objects = new ArrayList<Object>();
        while (cursor.hasNext()) {
            Document document = cursor.next();
            try {
                objects.add(BsonUtil.toBean(document, this.getClazz()));
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return objects;
    }

    @Override
    public List<Object> query(Bson bson) {
        FindIterable<Document> doIterable = this.getCollection().find(bson);
        MongoCursor<Document> cursor = doIterable.iterator();
        List<Object> objects = new ArrayList<Object>();
        while (cursor.hasNext()) {
            Document document = cursor.next();
            try {
                objects.add(BsonUtil.toBean(document, this.getClazz()));
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return objects;
    }

    @Override
    public Object queryOne(Bson bson) {
        Document document = this.getCollection().find(bson).first();
        try {
            return BsonUtil.toBean(document, this.getClazz());
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Object> query(Bson bson, Bson sort) {
        FindIterable<Document> doIterable = this.getCollection().find(bson)
                .sort(sort);
        MongoCursor<Document> cursor = doIterable.iterator();
        List<Object> objects = new ArrayList<Object>();
        while (cursor.hasNext()) {
            Document document = cursor.next();
            try {
                objects.add(BsonUtil.toBean(document, this.getClazz()));
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return objects;
    }

    @Override
    public Object queryOne(Bson bson, Bson sort) {
        Document document = this.getCollection().find(bson).sort(sort).first();
        try {
            return BsonUtil.toBean(document, this.getClazz());
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Object> query(Bson bson, Bson sort, int limit) {
        FindIterable<Document> doIterable = this.getCollection().find(bson)
                .sort(sort);
        if (limit > 0) {
            doIterable = doIterable.limit(limit);
        }
        MongoCursor<Document> cursor = doIterable.iterator();
        List<Object> objects = new ArrayList<Object>();
        while (cursor.hasNext()) {
            Document document = cursor.next();
            try {
                objects.add(BsonUtil.toBean(document, this.getClazz()));
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return objects;
    }

    @Override
    public List<Object> query(Bson bson, Bson sort, int limit, int skip) {
        FindIterable<Document> doIterable = this.getCollection().find(bson)
                .sort(sort);
        if (limit > 0) {
            doIterable = doIterable.limit(limit);
        }
        if (skip > 0) {
            doIterable = doIterable.skip(skip);
        }
        MongoCursor<Document> cursor = doIterable.iterator();
        List<Object> objects = new ArrayList<Object>();
        while (cursor.hasNext()) {
            Document document = cursor.next();
            try {
                objects.add(BsonUtil.toBean(document, this.getClazz()));
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return objects;
    }

    @Override
    public List<Object> query(Bson bson, Bson sort, Bson filter) {
        FindIterable<Document> doIterable = this.getCollection().find(bson)
                .sort(sort).filter(filter);
        MongoCursor<Document> cursor = doIterable.iterator();
        List<Object> objects = new ArrayList<Object>();
        while (cursor.hasNext()) {
            Document document = cursor.next();
            try {
                objects.add(BsonUtil.toBean(document, this.getClazz()));
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return objects;
    }

    @Override
    public Object queryOne(Bson bson, Bson sort, Bson Filter) {
        Document document = this.getCollection().find(bson).sort(sort)
                .filter(Filter).first();

        try {
            return BsonUtil.toBean(document, this.getClazz());
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public long count() {

        return this.getCollection().count();
    }

    @Override
    public long count(Bson bson) {
        // TODO Auto-generated method stub
        return this.getCollection().count(bson);
    }
}
复制代码

3. 帮助类:实现Document到Object 以及Object到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;

import org.bson.Document;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;

/*
 * 将mongo的文档转化为对象将对象转化为mongo文档
 * @author:maybo
 * @data:2016-2-1
 */
public class BsonUtil {
    public static <T> List<T> toBeans(List<Document> documents, Class<T> clazz)
            throws IllegalArgumentException, InstantiationException,
            IllegalAccessException, InvocationTargetException {
        List<T> list = new ArrayList<T>();
        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> T toBean(Document document, Class<T> 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();
            Column column = fields[i].getAnnotation(Column.class);
            Object bson = null;
            if (null != column && null != column.name()) {
                bson = document.get(column.name());
            } 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<Document> toBsons(List<Object> objs)
            throws IllegalArgumentException, SecurityException,
            IllegalAccessException, InvocationTargetException,
            NoSuchFieldException {
        List<Document> documents = new ArrayList<Document>();
        for (int i = 0; null != objs && i < objs.size(); i++) {
            documents.add(toBson(objs.get(i)));
        }
        return documents;
    }

    /*
     * 将对象转化为Bson文档
     * 
     * @param:对象
     * 
     * @param:类型
     * 
     * @return:文档
     */
    public static Document toBson(Object obj) throws IllegalArgumentException,
            IllegalAccessException, InvocationTargetException,
            SecurityException, NoSuchFieldException {
        if (null == obj) {
            return null;
        }
        Class<? extends Object> clazz = obj.getClass();
        Document document = new Document();
        Method[] methods = clazz.getDeclaredMethods();
        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; null != fields && i < fields.length; i++) {
            Column column = fields[i].getAnnotation(Column.class);// 获取列注解内容
            NotColumn notColumn = fields[i].getAnnotation(NotColumn.class);// 获取否列
            String key = null;// 对应的文档键值
            if (null != column && null != column.name()) {// 存在列映射取值
                key = column.name();
            } else if (null != notColumn) {// 不是列的情况
                continue;
            } else {
                key = fields[i].getName();// 默认情况通过属性名映射
                if ("id".equals(key)) {// 替换id为_id
                    key = "_id";
                }
            }
            String fieldName = fields[i].getName();
            /*
             * 获取对象属性值并映射到Document中
             */
            for (int j = 0; null != methods && j < methods.length; j++) {
                String methdName = methods[j].getName();
                if (null != fieldName && equalFieldAndGet(fieldName, methdName)) {
                    Object val = methods[j].invoke(obj);// 得到值
                    if (null == val) {
                        continue;
                    }
                    if (isJavaClass(methods[j].getReturnType())) {
                        if (methods[j].getReturnType().getName()
                                .equals("java.util.List")) {// 列表处理
                            @SuppressWarnings("unchecked")
                            List<Object> list = (List<Object>) val;
                            List<Document> documents = new ArrayList<Document>();
                            for (Object obj1 : list) {
                                documents.add(toBson(obj1));
                            }
                            document.append(key, documents);
                        } else {// 其它对象处理,基本类型
                            document.append(key, val);
                        }
                    } else {// 自定义类型
                        document.append(key, toBson(val));
                    }
                }
            }
        }
        return document;
    }

    /*
     * 是否是自定义类型】
     * 
     * false:是自定义
     */
    private static boolean isJavaClass(Class<?> clz) {
        return clz != null && clz.getClassLoader() == null;
    }

    /*
     * 将文档集转化为列表
     * 
     * @param:文档集
     * 
     * @param:属性类型
     * 
     * @return:返回列表
     */
    private static List<Object> colToList(Object bson, Field field)
            throws InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        ParameterizedType pt = (ParameterizedType) field.getGenericType();// 获取列表的类型
        List<Object> objs = new ArrayList<Object>();
        @SuppressWarnings("unchecked")
        MongoCollection<Document> cols = (MongoCollection<Document>) bson;
        MongoCursor<Document> cursor = cols.find().iterator();
        while (cursor.hasNext()) {
            Document child = cursor.next();
            @SuppressWarnings("rawtypes")
            Class clz = (Class) pt.getActualTypeArguments()[0];// 获取元素类型
            @SuppressWarnings("unchecked")
            Object obj = toBean(child, clz);
            System.out.println(child);
            objs.add(obj);

        }
        return objs;
    }

    /*
     * 比较setter方法和属性相等
     */
    private static boolean equalFieldAndSet(String field, String name) {
        if (name.toLowerCase().matches("set" + field.toLowerCase())) {
            return true;
        } else {
            return false;
        }
    }

    /*
     * 比较getter方法和属性相等
     */
    private static boolean equalFieldAndGet(String field, String name) {
        if (name.toLowerCase().matches("get" + field.toLowerCase())) {
            return true;
        } else {
            return false;
        }
    }
}
复制代码

4.用到的注解Column ,NotColumn,Table

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
Column:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
    public String name();
 
    public String text() default "这是一个属性映射";
}
N otColumn:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotColumn {
    public String text() default "不是属性字段";
}
Table:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
    public String name();
 
    public String text() default "表格映射";
}

  5. MongoObject 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import java.util.ArrayList;
import java.util.List;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ReadPreference;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
 
public class MongoObject {
    private List<String> hostPorts;
    private int port=27017;
    private String host="127.0.0.1";
    private int connectionsPerHost=5;// 每个主机的连接数
    private int threadsAllowedToBlockForConnectionMultiplier=30;// 线程队列数,它以上面connectionsPerHost值相乘的结果就是线程队列最大值。如果连接线程排满了队列就会抛出“Out
                                                                // // to get
                                                                // db”错误。
    private long maxWaitTime=5000;// 最大等待连接的线程阻塞时间
    private long connectTimeout=5000;// 连接超时的毫秒。0是默认和无限
    private long socketTimeout=5000;// socket超时。0是默认和无限
    private boolean autoConnectRetry=false;// 这个控制是否在一个连接时,系统会自动
 
    public void setHostPorts(List<String> hostPorts) {
        this.hostPorts = hostPorts;
    }
 
    public MongoObject() {
        // TODO Auto-generated constructor stub
    }
    public int getPort() {
        return port;
    }
 
    public void setPort(int port) {
        this.port = port;
    }
 
    public String getHost() {
        return host;
    }
 
    public void setHost(String host) {
        this.host = host;
    }
 
    public int getConnectionsPerHost() {
        return connectionsPerHost;
    }
 
    public void setConnectionsPerHost(int connectionsPerHost) {
        this.connectionsPerHost = connectionsPerHost;
    }
 
    public int getThreadsAllowedToBlockForConnectionMultiplier() {
        return threadsAllowedToBlockForConnectionMultiplier;
    }
 
    public void setThreadsAllowedToBlockForConnectionMultiplier(
            int threadsAllowedToBlockForConnectionMultiplier) {
        this.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier;
    }
 
    public long getMaxWaitTime() {
        return maxWaitTime;
    }
 
    public void setMaxWaitTime(long maxWaitTime) {
        this.maxWaitTime = maxWaitTime;
    }
 
    public long getConnectTimeout() {
        return connectTimeout;
    }
 
    public void setConnectTimeout(long connectTimeout) {
        this.connectTimeout = connectTimeout;
    }
 
    public long getSocketTimeout() {
        return socketTimeout;
    }
 
    public void setSocketTimeout(long socketTimeout) {
        this.socketTimeout = socketTimeout;
    }
 
    public boolean isAutoConnectRetry() {
        return autoConnectRetry;
    }
 
    public void setAutoConnectRetry(boolean autoConnectRetry) {
        this.autoConnectRetry = autoConnectRetry;
    }
 
    public MongoClient run() {
        if (null != hostPorts) {
            if (null != host && port > 0) {
                hostPorts.add(host + ":" + port);
            }
        else {
            hostPorts = new ArrayList<String>();
            if (null != host && port > 0) {
                hostPorts.add(host + ":" + port);
            else {
                return null;
            }
        }
        List<ServerAddress> addresses = new ArrayList<ServerAddress>();
        for (String hostPort : hostPorts) {
            String[] spits = hostPort.split(":");
            ServerAddress address = new ServerAddress(spits[0],
                    Integer.valueOf(spits[1]));
            addresses.add(address);
        }
 
        MongoClient client = new MongoClient(addresses, getConfOptions());
        return client;
    }
 
    @SuppressWarnings("deprecation")
    private MongoClientOptions getConfOptions() {
        return new MongoClientOptions.Builder()
                .socketKeepAlive(true)
                // 是否保持长链接
                .connectTimeout((intthis.connectTimeout)
                // 链接超时时间
                .socketTimeout((intthis.socketTimeout)
                // read数据超时时间
                .readPreference(ReadPreference.primary())
                // 最近优先策略
                .connectionsPerHost(this.connectionsPerHost)
                // 每个地址最大请求数
                .maxWaitTime((intthis.maxWaitTime)
                // 长链接的最大等待时间
                .threadsAllowedToBlockForConnectionMultiplier(
                        this.threadsAllowedToBlockForConnectionMultiplier) // 一个socket最大的等待请求数
                .writeConcern(WriteConcern.NORMAL).build();
    }
}

  6.MongoDB用于生产数据库对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import com.mongodb.client.MongoDatabase;
 
 
public class MongoDB{
    private String db;
    private MongoObject client;
    public void setClient(MongoObject client) {
        this.client = client;
    }
    public void setDb(String db) {
        this.db = db;
    }
public MongoDB(MongoObject client,String db){
    this.client=client;
    this.db=db;
}
public MongoDatabase excute(){
    return client.run().getDatabase(db);
}
}

  7.DaoImpl

复制代码
import java.util.List;


public class DaoImpl implements Dao{
    private MongoTemplate template;
private MongoSession session;
private String className;
public void setClassName(String className) {
    this.className = className;
}
public MongoSession getSession() {
    return session;
}
public DaoImpl(){}
public DaoImpl(MongoTemplate template,String className){
    this.template = template;
    this.className=className;
    try {
        this.session=template.session(Class.forName(className));
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
public void setTemplate(MongoTemplate template) {
    this.template = template;
    try {
        this.session=template.session(Class.forName(className));
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
    @Override
    public void save(Object obj) {
    this.session.save(obj);
    }

    @Override
    public void delete(Object obj) {
        try {
            this.session.delete(obj);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void update(Object obj) {
        this.session.update(obj);
    }

    @Override
    public Object find(Object obj) {
        // TODO Auto-generated method stub
        return this.session.find(obj);
    }

    @Override
    public List<Object> finds() {
        // TODO Auto-generated method stub
        return this.session.finds();
    }

    @Override
    public long total() {
        // TODO Auto-generated method stub
        return this.session.count();
    }

    @Override
    public List<Object> finds(int index, int offset) {
        // TODO Auto-generated method stub
        return this.session.query(null, null, offset, index);
    }

}
复制代码

8. Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class MongoDBTest {
    private static MongoTemplate template1;
    private static MongoTemplate template2;
    private static MongoTemplate template3;
    private static Dao dao1;
    private static Dao dao2;
    private static Dao dao3;
    static {
        MongoObject mongoObject = new MongoObject();
        mongoObject.setPort(12345);
        MongoDB demo1 = new MongoDB(mongoObject, "demo1");
        MongoDB demo2 = new MongoDB(mongoObject, "demo2");
        MongoDB demo3 = new MongoDB(mongoObject, "demo3");
        template1 = new MongoTemplate(demo1);
        template2 = new MongoTemplate(demo2);
        template3 = new MongoTemplate(demo3);
        dao1 = new DaoImpl(template1, "MidStu");
        dao2 = new DaoImpl(template2, "MidStu");
        dao3 = new DaoImpl(template3, "MidStu");
    }
 
    @Test
    public void save() {
 
        MidStu midStu = new MidStu();
        midStu.setHabit("zuqiu");
        midStu.setId("saflfgsddsf35");
        dao1.save(midStu);
        MidStu midStuFind = new MidStu();
        midStuFind.setId("saflfgsddsf35");
        System.out.println(dao1.find(midStuFind).toString());
 
        dao2.save(midStu);
 
        System.out.println(dao2.find(midStuFind).toString());
 
        dao3.save(midStu);
        System.out.println(dao3.find(midStuFind).toString());
    }
}
分享到:
评论

相关推荐

    古典诗歌鉴赏——单诗精练 单诗精练二.docx

    《古典诗歌鉴赏——单诗精练 单诗精练二》这篇文档是关于古典诗歌分析的资料,其中主要探讨了一首与韩愈左迁至蓝关示侄孙湘相关联的诗作。通过对诗中意象、情感的解读,我们可以深入理解诗人的情感表达和创作技巧。 ...

    高一年下期总复习二成语复习PPT课件.ppt

    4. 陈残云——风卷残云,形容快速扫荡,不留痕迹。 5. 陶成章——出口成章,形容口才好,出口即文章。 6. 杜鹏程——鹏程万里,象征远大的前程。 7. 王任重——任重道远,表示责任重大,道路长远。 8. 马致远——...

    小学语文趣味练习50题.doc

    通过不同语境下的“望”字,学生可以理解同一词在不同情境中的变化,提高语言表达的准确性和丰富性。 这些练习题旨在通过寓教于乐的方式,提升小学生对语文的热爱和理解,帮助他们掌握更多的词汇和语言技巧,同时...

    人教版三年级语文阅读训练试题(含答案).doc

    3. 反义词:题目中出现了"浓——〔〕慢——〔〕",这是考察反义词的理解和识别,反义词是词汇学习的重要部分,有助于提升语言表达的丰富性。 4. 语境理解与段落分析:如"1.全文有个自然段,“天空泛起了粉红色的...

    【少儿综合素质训练】经典宋词《菩萨蛮》精选六首.doc

    词中描绘的平林、烟雾、寒山等自然景象,营造出一种深秋的凄凉氛围,映射出词人内心的孤独与愁绪。词句间的紧密联系,构建出一个完整的意境,展现了李白的高超艺术才华。 李清照的《菩萨蛮・归鸿声断残云碧》则以其...

    小学三年级语文阅读训练试题及答案5篇.doc

    1. 小学语文阅读理解技巧:文章中提到了一篇关于“观日出”的短文,这是小学语文阅读理解中常见的题材。学生需要掌握如何从文章中提取关键信息,例如文中提到的日出的过程,包括残云散尽、晨星闪烁、霞光变色、日出...

    公开课中华文化的智慧之花-熟语之成语新人教版.ppt

    这篇内容主要围绕着中华文化的智慧之花——熟语展开,特别是成语,它是熟语的一种重要形式。熟语是汉语中经过长时间使用而形成的固定短语,具有特定的意义,不能随意改变其结构。成语通常由四个字组成,但也存在二字...

    北京市海淀区2011届高三查漏补缺语文试题.doc

    2. **景物描写**:许浑诗中运用了远近结合、化静为动的手法,通过“红叶”、“长亭”、“残云”、“疏雨”等意象,描绘了一幅秋日行旅画面,以动衬静,展现了环境的宁静深远。 3. **词的理解与赏析**:林仰的《少年...

    三年级7篇语文阅读训练试题及答案.doc

    3. 描述性写作:第一篇短文生动描绘了日出的过程,从残云、晨星、霞光的变化,到太阳冉冉升起,最后是天空和大海被金光照亮。这种写作方式展示了如何用文字构建视觉画面,有助于提升学生的语言表达和形象思维能力。 ...

    诗歌鉴赏之景物分析题型答题技巧.doc

    在古代诗歌鉴赏中,景物分析是一种常见的题型,旨在考察考生对于诗词中景物描写的理解及其艺术手法的把握。通过对景物特点、描写角度、手法等方面的分析,可以深入领略诗歌的意境与情感。 一、分析景物描写的特点 ...

    极有趣味的语文游戏-适合语文课堂教学.doc

    【语文游戏】是一种创新的教学方式,能够激发学生学习语文的兴趣,增强课堂的互动性。在游戏中,学生通过参与各种活动,可以加深对成语、俗语、歇后语等语言文化的理解和记忆。 1. **成语对对子**:这是一种训练...

    axios node_module包

    此外,响应对象包含了诸如 status、data、headers 和 config 等属性,便于处理和分析返回结果。 5. **拦截器**: Axios 提供了请求和响应拦截器,可以对请求和响应进行预处理。例如,添加全局的请求头: ```...

    初中语文 古诗文赏析 许浑《秋日赴阙题潼关驿楼》原文、注释、译文及赏析.doc

    诗中通过描绘红叶、长亭、残云、疏雨等景象,展现了秋日旅途的寂寥与壮丽,同时也表达了诗人对渔樵生活的向往。 诗的开头“红叶晚萧萧,长亭酒一瓢。”以秋日的红叶和长亭饮酒描绘了离别的凄凉氛围,展现出诗人的离...

    【创新设计】(福建专用)2014高三语文一轮复习 训练6古代诗歌鉴赏(二)新人教版

    【创新设计】(福建专用)2014高三语文一轮复习 训练6古代诗歌鉴赏(二)新人教版的资源属于语文学习中的古诗词鉴赏部分,主要锻炼学生的诗词理解与分析能力。这部分训练包含几首唐诗的解析,通过提问的形式引导学生...

    描写夏天炎热的诗句大全.doc

    唐代诗人岑参在《水亭送华阴王少府还县》中写道:“残云收夏暑,新雨带秋岚。”这句诗描绘了夏季过半时,残余的暑气在新雨的洗礼下逐渐消退,而秋天的雾气也随之而来。诗中的“夏半阴气始”形象地刻画了农历五月半后...

    江苏专版2020高考语文二轮复习古典诗歌鉴赏__单诗精练单诗精练二寄韩潮州愈含解析201911281116

    通过对一首寄给韩潮州愈的诗进行解读,探讨了诗人的情感表达和艺术手法。 首先,诗歌作为和诗的依据体现在以下几个方面:1)诗人提到“隔岭篇章”,这直接引用了韩愈《左迁》诗的内容,表明是对此诗的回应。2)“峰悬...

    【创新设计】(辽宁专用)2014高考语文一轮复习 限时训练15古代诗歌鉴赏(二)新人教版

    【创新设计】(辽宁专用)2014高考语文一轮复习 限时训练15古代诗歌鉴赏(二)新人教版的课程旨在帮助学生提升古代诗歌鉴赏的能力。古代诗歌是中国传统文化的重要载体,通过鉴赏可以理解诗人的情感,增强语言感知力和...

    JavaScript语言精粹

    JavaScript语言精粹是一本深入探讨JavaScript编程技巧与实践的经典书籍,旨在帮助开发者挖掘这门语言的潜力并提升其编程技能。这本书涵盖了JavaScript的核心概念、高级特性以及最佳实践,是JavaScript初学者和进阶者...

    雅虎给出的34条优化网站访问速度加快方法

    在互联网时代,网站访问速度是决定用户体验和网站成功的关键因素之一。雅虎,作为早期的互联网巨头,基于其丰富的经验和深入的研究,总结出了34条优化网站访问速度的方法,这些建议对于任何希望提高网站性能的开发者...

Global site tag (gtag.js) - Google Analytics