1. 程式人生 > >Java連線Mongo

Java連線Mongo

    最近剛剛做完一個小東西,用到了Mongo,Java和maven由於是第一次使用這三個東西,期間遇到了不少坑,現將整個過程記錄下來。

    1.連線Mongo庫

     在pom.xml中新增依賴

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.4.1</version>
</dependency>

     2.建立MongoHelper

public class MongoHelper {
    private static final String DBName = "dbname";
    private static MongoClient mongoClient ;
    public MongoHelper(){
    }
    
    //開啟資料庫連線
    public static MongoDatabase MongoStart(){
        mongoClient = new MongoClient("localhost",27017);
        MongoDatabase mongoDatabase = mongoClient.getDatabase(DBName);
        return mongoDatabase;
    }
    //關閉連線
    public static void close() {
        if (mongoClient != null) {
            mongoClient.close();
            mongoClient = null;
        }
    }
}

  3.往Mongo裡面插入一條資料

    當時做的時候發現Mongo好像不能直接往庫裡面插入一個實體類,必須得使用Document物件才可以,於是自己寫了一個工具類,可以將實體類轉換成Document物件,然後再插入到庫中。

public class ConvClass {
    private Object mobj;
    public ConvClass(Object obj) {
        mobj = obj;
    }
    private static Object getFieldValueByFieldName(String fieldName, Object object) {
        try {
            Field field = object.getClass().getDeclaredField(fieldName);
            boolean access = field.isAccessible();
            if (!access) {
                field.setAccessible(true);
            }
            return  field.get(object);
        } catch (Exception e) {
            return null;
        }
    }

    public Document getDocument() {
        Document document = new Document();
        Field[] fields =  mobj.getClass().getDeclaredFields();
        for(int i=0 ;i<fields.length;i++){
            if(fields[i].getType().equals(Date.class)){
                Date date = (Date)getFieldValueByFieldName(fields[i].getName(),mobj);
                document.append(fields[i].getName(),date);
            }
            ...
            document.append(fields[i].getName(),getFieldValueByFieldName(fields[i].getName(),mobj));

        }
        return document;
    }
}

     呼叫ConvClass並插入資料到Mongo庫中

    public static void insert(Object obj){
        MongoCollection<Document> collection = MongoHelerp.MongoStart().getCollection(obj.getClass().getSimpleName());
        ConvClass convClass = new ConvClass(obj);
        Document document = convClass.getDocument();
        collection.insertOne(document);
        MongoHelper.close();
} 

    4.單表查詢返回List

    public static List getObjList (Object obj) {
        MongoCollection<Document> collection = MongoHelerp.MongoStart().getCollection(obj.getClass().getSimpleName());
        FindIterable<Document> iterable = collection.find();
        final List<Object> list = new ArrayList<>();
        iterable.forEach(new Block<Document>() {
            @Override
            public void apply(Document arg0) {
                try {
                    BeanUtils.copyProperties(obj,arg0);
                    list.add(obj);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        });
        MongoHelper.close();
        return list;
    }