通過java反射實現簡單的關於MongoDB的對象關系映射(ORM).


    通過閱讀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

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 

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((int) this.connectTimeout)
				// 鏈接超時時間
				.socketTimeout((int) this.socketTimeout)
				// read數據超時時間
				.readPreference(ReadPreference.primary())
				// 最近優先策略
				.connectionsPerHost(this.connectionsPerHost)
				// 每個地址最大請求數
				.maxWaitTime((int) this.maxWaitTime)
				// 長鏈接的最大等待時間
				.threadsAllowedToBlockForConnectionMultiplier(
						this.threadsAllowedToBlockForConnectionMultiplier) // 一個socket最大的等待請求數
				.writeConcern(WriteConcern.NORMAL).build();
	}
}

  6.MongoDB用於生產數據庫對象

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

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());
	}
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM