java 操作MongoDB

需要的jar包和安装包:https://pan.baidu.com/s/1P6ZxuWFtKrTU7eRRV9OkAg 密码: kf76

我用Robo 3T 1.1.1作为MongoDB的GUI界面,有需要可以用,用cmd控制台也行。

看看Robo 3T界面

java 操作MongoDB_第1张图片

失效给[email protected]发送邮件。

代码需要一定的java基础,泛型he

1.entity实体类

package entity;

public class Emp {

    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Emp{" + "id=" + id + ", name='" + name + '\'' + '}';
    }
}

2.util 类(MongoDBUtil1封装MongoDB操作,Bean2DBObject转换对象

 
  
package util;

import com.mongodb.*;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class MongoDBUtil1 {

    private static Mongo mongo = null;
    private MongoDBUtil1(){
        super();
    }

    private static String host;
    private static int port;
    private static String dbName;

    static {
        InputStream in = null;
        Properties prop = new Properties();
        try{
            if(in==null) in = MongoDBUtil1.class.getResourceAsStream("../MongoDB.properties");
            prop.load(in);
            host = prop.getProperty("host");
            port = Integer.parseInt(prop.getProperty("port"));
            dbName = prop.getProperty("dbName");
        }catch (IOException e){
            System.out.println("读配置文件出错");
            e.printStackTrace();
        }finally {
            System.out.println("读配置文件end");
        }

    }

    public static void insert(Object obj,String table){
        if (mongo==null) mongo = new Mongo(host,port);
        try{
            DB db = mongo.getDB(dbName);
            DBCollection dbCollection = db.getCollection(table);
            if (dbCollection==null) {
                DBObject dbObj = new BasicDBObject();
                dbCollection = db.createCollection(table,dbObj);
            }
            dbCollection.insert(Bean2DBObject.bean2DBObject(obj));
        }catch (Exception e){
            System.out.println("插入出错");
        }finally {
            if (mongo!=null) mongo.close();
        }
    }

    public static List find(Object obj,String table,String field) {
        if (mongo==null) mongo = new Mongo(host,port);
        try{
            DB db = mongo.getDB(dbName);
            DBCollection dbCollection = db.getCollection(table);
            if (dbCollection==null) {
                DBObject dbObj = new BasicDBObject();
                dbCollection = db.createCollection(table,dbObj);
            }
            BasicDBObject searchQuery = new BasicDBObject();
            Object fieldValue=null;

            Class clazz=obj.getClass();
            BeanInfo beanInfo= Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] pds=beanInfo.getPropertyDescriptors();
            for(PropertyDescriptor pd:pds){
                if(pd.getName().equals(field)){
                    System.out.println(field+":"+pd.getReadMethod());
                    Method getter=pd.getReadMethod();
                    if (!getter.isAccessible()) getter.setAccessible(true);
                    fieldValue = getter.invoke(obj);
                }
            }

            if (fieldValue==null) {
                return null;
            } else if (fieldValue instanceof Integer) {
                // 判断变量的类型
                int value = ((Integer) fieldValue).intValue();
                searchQuery.put(field, value);
            } else if (fieldValue instanceof String) {
                String value = (String) fieldValue;
                searchQuery.put(field, value);
            } else if (fieldValue instanceof Double) {
                double value = ((Double) fieldValue).doubleValue();
                searchQuery.put(field, value);
            } else if (fieldValue instanceof Float) {
                float value = ((Float) fieldValue).floatValue();
                searchQuery.put(field, value);
            } else if (fieldValue instanceof Long) {
                long value = ((Long) fieldValue).longValue();
                searchQuery.put(field, value);
            } else if (fieldValue instanceof Boolean) {
                boolean value = ((Boolean) fieldValue).booleanValue();
                searchQuery.put(field, value);
            } else if (fieldValue instanceof Date) {
                Date value = (Date) fieldValue;
                searchQuery.put(field, value);
            }
            DBCursor cur = dbCollection.find(searchQuery);
            List results = new ArrayList();
            while (cur.hasNext()){
                results.add(cur.next());
            }
            return results;
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            if (mongo!=null) mongo.close();
        }
        return null;
    }

}
 
  
package util;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

import java.lang.reflect.Field;
import java.util.Date;

public class Bean2DBObject {

    /**
     * 将实体Bean对象转换为DBObject
     */
    public static <T> DBObject bean2DBObject(T bean) throws IllegalAccessException {
        if(bean == null) return null;
        DBObject dbObject = new BasicDBObject();
        //获得对象类的属性域
        Field[] fields = bean.getClass().getDeclaredFields();
        for(Field field:fields){
            //获得变量属性名
            String varName = field.getName();
            if(!field.isAccessible())field.setAccessible(true);
            Object param = field.get(bean);
            //System.out.println(param);
            if (param==null){
                continue;
            }else if (param instanceof Integer) {
                // 判断变量的类型
                int value = ((Integer) param).intValue();
                dbObject.put(varName, value);
            } else if (param instanceof String) {
                String value = (String) param;
                dbObject.put(varName, value);
            } else if (param instanceof Double) {
                double value = ((Double) param).doubleValue();
                dbObject.put(varName, value);
            } else if (param instanceof Float) {
                float value = ((Float) param).floatValue();
                dbObject.put(varName, value);
            } else if (param instanceof Long) {
                long value = ((Long) param).longValue();
                dbObject.put(varName, value);
            } else if (param instanceof Boolean) {
                boolean value = ((Boolean) param).booleanValue();
                dbObject.put(varName, value);
            } else if (param instanceof Date) {
                Date value = (Date) param;
                dbObject.put(varName, value);
            }
        }
        return dbObject;
    }
}
package util;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

import java.lang.reflect.Field;
import java.util.Date;

public class Bean2DBObject {

    /**
     * 将实体Bean对象转换为DBObject
     */
    public static <T> DBObject bean2DBObject(T bean) throws IllegalAccessException {
        if(bean == null) return null;
        DBObject dbObject = new BasicDBObject();
        //获得对象类的属性域
        Field[] fields = bean.getClass().getDeclaredFields();
        for(Field field:fields){
            //获得变量属性名
            String varName = field.getName();
            if(!field.isAccessible())field.setAccessible(true);
            Object param = field.get(bean);
            //System.out.println(param);
            if (param==null){
                continue;
            }else if (param instanceof Integer) {
                // 判断变量的类型
                int value = ((Integer) param).intValue();
                dbObject.put(varName, value);
            } else if (param instanceof String) {
                String value = (String) param;
                dbObject.put(varName, value);
            } else if (param instanceof Double) {
                double value = ((Double) param).doubleValue();
                dbObject.put(varName, value);
            } else if (param instanceof Float) {
                float value = ((Float) param).floatValue();
                dbObject.put(varName, value);
            } else if (param instanceof Long) {
                long value = ((Long) param).longValue();
                dbObject.put(varName, value);
            } else if (param instanceof Boolean) {
                boolean value = ((Boolean) param).booleanValue();
                dbObject.put(varName, value);
            } else if (param instanceof Date) {
                Date value = (Date) param;
                dbObject.put(varName, value);
            }
        }
        return dbObject;
    }
}

3.dao类

import entity.Emp;

import java.util.List;

public interface EmpDao {

    public void insert(Emp e);
    public List find(Emp e);
    public void update(Emp e);
    public void delete(Emp e);
}

4.daoImpl实现类

package daoImpl;

import dao.EmpDao;
import entity.Emp;
import util.MongoDBUtil1;

import java.util.List;

public class EmpDaoImpl implements EmpDao {

    @Override
    public void insert(Emp e) {
        MongoDBUtil1.insert(e,"emp");
        System.out.println("插入完毕");
    }

    @Override
    public List find(Emp e) {
        List list = MongoDBUtil1.find(e,"emp","id");
        return list;
    }

    @Override
    public void update(Emp e) {

    }

    @Override
    public void delete(Emp e) {

    }
}

5.resources资源(MongoDB.properties)

host=localhost
port=27017
dbName=ChatRoom

6.测试类

package test;

import dao.EmpDao;
import daoImpl.EmpDaoImpl;
import entity.Emp;
import org.junit.Test;

public class TestDB1 {

    @Test
    public void test1() {
        Emp emp = new Emp();
        emp.setId(1);
        emp.setName("donghui");
        EmpDao dao = new EmpDaoImpl();
        dao.insert(emp);
    }

    @Test
    public void test2() {
        Emp emp = new Emp();
        emp.setId(1);
        emp.setName("donghui");
        EmpDao dao = new EmpDaoImpl();
        System.out.println(dao.find(emp));
    }
}

你可能感兴趣的:(java,MongoDB,反射,泛型,java)