NoSQL之MongoDB的CRUD操作

MongoDB是一個基於分佈式文件存儲的數據庫,是NoSQL實現的一種,支持Java.NoSQL越來越受到IT界的重視,所以掌握NoSQL技術,也非常重要。

在空閒時間寫了Mongo的CRUD代碼,請大家參考。有什麼地方不好或意見,大家可以提出!

 

import java.lang.reflect.Field;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONObject;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;


/**
 * 
 * <b>功能:實現MongoDB的CRUD操作</b><br> 
 * <br>
 * <b>完整路徑:</b> .MongoUtil2 <br> 
 * <b>創建日期:</b> 2012-4-26 上午10:54:56 <br>
 * @author <a href="mailto:[email protected]">dwc</a><br>
 *         <a href="http://www.shareinfo.com.cn">Shenzhen Share Info System Co.,Ltd.</a>
 * @version 1.0, 2012-4-26
 */
public class MongoDBUtil{
	private static final String URL="localhost";//連接地址
	private static final int PORT=27017;//連接端口
	private static final String DB="test";//連接DB

	private static Mongo mg = null;
	private static DB db=null;
	private DBCollection conn=null;

	/**
	 * 
	 * <b>功能:單例模式</b><br>
	 * <b>提示:在這裏DB理解爲數據庫,DBCollection理解爲表</b><br>
	 * <br>
	 * @修改者 ~ 鄧萬川, 2012-4-26
	 * @return DB
	 */
	private static synchronized  DB getDb(){
		try {
			if(db==null){
				mg = new Mongo(URL, PORT);
				//獲取 DB;如果默認沒有創建,mongodb會自動創建
				db = mg.getDB(DB);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return db;
	}

	/**
	 * 
	 * <b>功能:獲取連接</b><br>
	 * <br>
	 * @修改者 ~dwc, 2012-4-26
	 * @param connName 表連接名稱
	 * @return DBCollection 表連接對象
	 */
	public static DBCollection  getConn(String connName){
		getDb();
		return db.getCollection(connName);
	}

	/**
	 * 
	 * <b>功能:對象銷燬,清除內存</b><br>
	 * <br>
	 * @修改者 ~ dwc 2012-4-26 void
	 */
	public void destory() {
		if (mg != null)
			mg.close();
		mg = null;
		db = null;
		conn = null;
		System.gc();
	}

	/**
	 * 
	 * <b>功能:根據Mongo對象條件查詢所有數據</b><br>
	 * <br>
	 * @修改者 ~ dwc, 2012-4-26
	 * @param dbObject Mongo條件對象
	 * @param connName 表連接名稱
	 * @param className 獲取對象的類名稱
	 * @return
	 * @throws Exception List 返回集合
	 */
	public List findAll(DBObject dbObject,String connName,String className)throws Exception{
		List<Object> resultList=new ArrayList<Object>();
		try {
			conn=getConn(connName);
			List<DBObject> list = conn.find(dbObject).toArray();
			for(DBObject dbObj:list){
				Object obj= DB2Bean(dbObj,className);
				resultList.add(obj);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}finally{
			destory();
		}
		return resultList;
	}
	
	/**
	 * 
	 * <b>功能:根據自定義對象條件查詢所有數據</b><br>
	 * <br>
	 * @修改者 ~ dwc, 2012-4-26
	 * @param object 定義條件對象
	 * @param connName 表連接名稱
	 * @param className 獲取對象的類名稱
	 * @return
	 * @throws Exception List 返回集合
	 */
	public List findAll(Object object,String connName,String className)throws Exception{
		List<Object> resultList=new ArrayList<Object>();
		try {
			conn=getConn(connName);
			List<DBObject> list = conn.find(bean2DB(object)).toArray();
			for(DBObject dbObj:list){
				Object obj= DB2Bean(dbObj,className);
				resultList.add(obj);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}finally{
			destory();
		}
		return resultList;
	}


	/**
	 * 
	 * <b>功能:根據Mongo對象查詢單個數據</b><br>
	 * <br>
	 * @修改者 ~ dwc, 2012-4-26
	 * @param dbObject   Mongo條件對象
	 * @param connName 表連接名稱
	 * @param className 獲取對象的類名稱
	 * @return 
	 * @throws Exception Object 返回對象
	 */
	public Object findOne(DBObject dbObject,String connName,String className)throws Exception{
		Object obj=null;
		try {
			conn=getConn(connName);
			DBObject result = conn.findOne(dbObject);
			obj=DB2Bean(dbObject, className);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}finally{
			destory();
		}
		return obj;
	}
	
	
	/**
	 * 
	 * <b>功能:根據自定義對象查詢單個數據</b><br>
	 * <br>
	 * @修改者 ~ dwc, 2012-4-26
	 * @param object   自定義條件對象
	 * @param connName 表連接名稱
	 * @param className 獲取對象的類名稱
	 * @return
	 * @throws Exception Object 返回對象
	 */
	public Object findOne(Object object,String connName,String className)throws Exception{
		Object obj=null;
		try {
			conn=getConn(connName);
			DBObject result = conn.findOne(bean2DB(object));
			obj=DB2Bean(result, className);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			destory();
		}
		return obj;
	}
	
	/**
	 * 
	 * <b>功能:根據條件id查詢數據</b><br>
	 * <br>
	 * @修改者 ~ dwc, 2012-4-26
	 * @param id 條件id
	 * @param connName  表連接名稱
	 * @param className 獲取對象的類名稱
	 * @return
	 * @throws Exception Object 返回對象
	 */
	public Object findOneById(Object id,String connName,String className)throws Exception{
		Object obj=null;
		try {
			conn=getConn(connName);
			DBObject dbObject = conn.findOne(new BasicDBObject("_id",id));
			obj=DB2Bean(dbObject, className);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}finally{
			destory();
		}
		return obj;
	}

	/**
	 * 
	 * <b>功能:增加數據</b><br>
	 * <br>
	 * @修改者 ~ dwc, 2012-4-26
	 * @param obj  要增加對象
	 * @param connName  表連接名稱
	 * @return
	 * @throws Exception int 返回影響結果
	 */
	public int add(Object obj,String connName)throws Exception{
		int result=-1;
		try {
			conn=getConn(connName);
			DBObject dbObject= (DBObject) JSON.parse(JSONObject.fromObject(obj).toString());
			result=conn.insert(dbObject).getN();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}finally{
			destory();
		}
		return result;
	}
	
	/**
	 * 
	 * <b>功能:增加數據</b><br>
	 * <br>
	 * @修改者 ~ dwc, 2012-4-26
	 * @param dbObject 封裝對象的數據
	 * @param connName  表連接名稱
	 * @return
	 * @throws Exception int  返回影響結果
	 */
	public int add(DBObject dbObject,String connName)throws Exception{
		int result=-1;
		try {
			conn=getConn(connName);
			result=conn.insert(dbObject).getN();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}finally{
			destory();
		}
		return result;
	}

	/**
	 * 
	 * <b>功能:修改數據</b><br>
	 * <br>
	 * @修改者 ~ dwc, 2012-4-26
	 * @param value 修改的數據
	 * @param where 修改條件
	 * @param connName  表連接名稱
	 * @return
	 * @throws Exception int 返回影響結果
	 */
	public int update(DBObject value,DBObject where,String connName) throws Exception{
		int result=-1;
		try {
			conn=getConn(connName);
			result= conn.update(where, value).getN();
		} catch (MongoException e) {
			e.printStackTrace();
			throw new Exception();
		}finally{
			destory();
		}
		return result;
	}
	

	/**
	 * 
	 * <b>功能:修改數據</b><br>
	 * <br>
	 * @修改者 ~ dwc, 2012-4-26
	 * @param value 修改的數據
	 * @param where 修改條件
	 * @param connName  表連接名稱
	 * @return
	 * @throws Exception int 返回影響結果
	 */
	public int update(Object value,Object where,String connName)throws Exception {
		int result=-1;
		try {
			conn=getConn(connName);
			result= conn.update(bean2DB(where),bean2DB(value)).getN();
		} catch (MongoException e) {
			e.printStackTrace();
			throw new Exception();
		}finally{
			destory();
		}
		return result;
	}

	/**
	 * 
	 * <b>功能:根據條件刪除數據</b><br>
	 * <br>
	 * @修改者 ~ dwc, 2012-4-26
	 * @param obj 要刪除的對象
	 * @param connName 表連接名稱
	 * @return
	 * @throws Exception int 返回影響結果
	 */
	public int remove(Object obj,String connName) throws Exception{
		int result=-1;
		try {
			conn=getConn(connName);
			result= conn.remove(bean2DB(obj)).getN();
		} catch (MongoException e) {
			e.printStackTrace();
			throw new Exception();
		}finally{
			destory();
		}
		return result;
	}
	
	/**
	 * 
	 * <b>功能:根據條件刪除數據</b><br>
	 * <br>
	 * @修改者 ~ dwc, 2012-4-26
	 * @param dbObject  要刪除的數據
	 * @param connName 表連接名稱
	 * @return
	 * @throws Exception int 返回影響結果
	 */
	public int remove(DBObject dbObject,String connName)throws Exception {
		int result=-1;
		try {
			conn=getConn(connName);
			result= conn.remove(dbObject).getN();
		} catch (MongoException e) {
			e.printStackTrace();
			throw new Exception();
		}finally{
			destory();
		}
		return result;
	}
	
	/**
	 * 
	 * <b>功能:根據條件得到數據總和</b><br>
	 * <br>
	 * @修改者 ~ dwc, 2012-4-26
	 * @param dbObject 條件對象
	 * @param connName  表連接名稱
	 * @return
	 * @throws Exception int 返回影響結果
	 */
	public int getCount(DBObject dbObject,String connName)throws Exception{
		int result=0;
		try {
			conn=getConn(connName);
			result=conn.find(dbObject).count();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}
		return result;
	}
	
	/**
	 * 
	 * <b>功能:根據條件得到數據總和</b><br>
	 * <br>
	 * @修改者 ~ dwc, 2012-4-26
	 * @param obj 條件對象
	 * @param connName 表連接名稱
	 * @return
	 * @throws Exception int 返回影響結果
	 */
	public int getCount(Object obj,String connName)throws Exception{
		int result=0;
		try {
			conn=getConn(connName);
			result=conn.find(bean2DB(obj)).count();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 
	 * <b>功能:將自定義對象轉換爲Mongo對象</b><br>
	 * <br>
	 * @修改者 ~ dwc, 2012-4-26
	 * @param obj 自定義對象
	 * @return DBObject Mongo對象
	 */
	public static DBObject bean2DB(Object obj)throws Exception{
		DBObject dbObject=new BasicDBObject();
		Class<? extends Object> clazz=obj.getClass();
		Field [] fields=clazz.getDeclaredFields();
		for(Field field:fields){
			String fieldName=field.getName();
			String methodName="get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1,fieldName.length());
			Method method=null;
			Object  resultObj=null;
			try {
				method=clazz.getMethod(methodName);
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
			try {
				resultObj=method.invoke(obj);
			} catch (Exception e) {
				continue;
			}
			if(resultObj!=null&&!resultObj.equals("")){
				dbObject.put(fieldName, resultObj);
			}
		}
		return dbObject;
	}
	
	/**
	 * 
	 * <b>功能:將Mongo對象轉換爲自定義對象</b><br>
	 * <br>
	 * @修改者 ~ 鄧萬川, 2012-4-26
	 * @param dbObject Mongo對象
	 * @param className 要轉換的類名稱
	 * @return
	 * @throws Exception Object
	 */
	public static Object DB2Bean(DBObject dbObject,String className) throws Exception{
		Class clazz=Class.forName(className);
		Object obj=clazz.newInstance();
		Field [] fields=clazz.getDeclaredFields();
		for(Field field:fields){
			String fieldName=field.getName();
			String methodName="set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1,fieldName.length());
			Method method=null;
			Object  resultObj=null;
			try {
				method=clazz.getMethod(methodName,new Class[]{field.getType()});
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
			resultObj=dbObject.get(fieldName);
			try {
				resultObj=method.invoke(obj,new Object[]{resultObj});
			} catch (Exception e) {
				continue;
			}
		}
		return obj;
	}
}

 

 

public class Student {
	private Object _id;
	private String name;
	private String age;
	
	
	public Object get_id() {
		return _id;
	}
	public void set_id(Object_id) {
		this._id = _id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	
	
}
 

 

import java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.text.TabableView;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.bson.BSONObject;
import org.bson.types.ObjectId;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.mongodb.BasicDBObject;
import com.mongodb.Bytes;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.QueryOperators;
import com.mongodb.util.JSON;


/**
 * 
 * <b>功能:MongoDB測試類</b><br> 
 * <br>
 * <b>完整路徑:</b> .MongoTest <br> 
 * <b>創建日期:</b> 2012-4-26 下午2:15:41 <br>
 * @author <a href="mailto:[email protected]">dwc</a><br>
 *         <a href="http://www.shareinfo.com.cn">Shenzhen Share Info System Co.,Ltd.</a>
 * @version 1.0, 2012-4-26
 */
public class MongoDBTest{
	MongoDBUtil mu=new MongoDBUtil();
	@Test
	public void find(){
		//List<DBObject> list=queryAll(null, "student");
		try {
			Student stu=new Student();
			List<Student> list=mu.findAll(stu,"student",Student.class.getName());
			for (Student result : list) {
					System.out.println("name="+result.getName());
					System.out.println("age="+result.getAge());
					System.out.println("========================");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Test
	public void add() {
		Student stu=new Student();
		stu.setAge("24");
		stu.setName("tom");
		try {
			mu.add(stu, "stu");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Test
	public void update(){
		try {
			Student where=new Student();
			where.setAge("22");
			where.setName("tom");
			
			Student value=(Student) mu.findOne(where, "stu", where.getClass().getName());
			value.setAge("25");
			value.setName("joke");
			System.out.println(mu.update(value,where,"stu"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void remove(){
		try {
			Student where=new Student();
			where.setAge("25");
			where.setName("joke");
			mu.remove(where, "stu");
		} catch (Exception e) {
			e.printStackTrace();
		}
	
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章