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


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页