`
dengwanchuan
  • 浏览: 45449 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
最近访客 更多访客>>
社区版块
存档分类
最新评论

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:dengwanchuan@shareinfo.com.cn">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:dengwanchuan@shareinfo.com.cn">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();
		}
	
	}
}
分享到:
评论
7 楼 AallenXu 2013-06-09  
我直接用您的代码,运行时发现报好多java.lang.NoSuchMethodException...如何解决啊?!!!  不知道现在你还有时间帮助一下不?
6 楼 hyneng 2012-05-30  
dengwanchuan 写道
hyneng 写道
再说一下我遇到的问题。
如果想按测试类MongoDBTest的add-->find-->update-->find-->remove这个流程跑进来,要注意几点。
1.find方法的表名得注意了,要不,添加进去后查看不到添加的数据,student->stu,
List<Student> list=mu.findAll(stu,"student",Student.class.getName());
2.update方法,如果按照where找不到对象,会出现空指针异常,所以 where.setAge("22");  应改为 where.setAge("24");  在此插一句,是不是应该处理这种情况下空针异常的问题



对不起,回复晚了,第二个问题,的确是要处理空指针异常.

写得挺好的
5 楼 dengwanchuan 2012-05-30  
hyneng 写道
再说一下我遇到的问题。
如果想按测试类MongoDBTest的add-->find-->update-->find-->remove这个流程跑进来,要注意几点。
1.find方法的表名得注意了,要不,添加进去后查看不到添加的数据,student->stu,
List<Student> list=mu.findAll(stu,"student",Student.class.getName());
2.update方法,如果按照where找不到对象,会出现空指针异常,所以 where.setAge("22");  应改为 where.setAge("24");  在此插一句,是不是应该处理这种情况下空针异常的问题



对不起,回复晚了,第二个问题,的确是要处理空指针异常.
4 楼 steafler 2012-05-10  
灰常不错呀
3 楼 hyneng 2012-05-05  
再说一下我遇到的问题。
如果想按测试类MongoDBTest的add-->find-->update-->find-->remove这个流程跑进来,要注意几点。
1.find方法的表名得注意了,要不,添加进去后查看不到添加的数据,student->stu,
List<Student> list=mu.findAll(stu,"student",Student.class.getName());
2.update方法,如果按照where找不到对象,会出现空指针异常,所以 where.setAge("22");  应改为 where.setAge("24");  在此插一句,是不是应该处理这种情况下空针异常的问题
2 楼 hyneng 2012-05-05  
还有加以下包:
ezmorph-1.0.2.jar
commons-beanutils-1.7.0.jar
commons-collections-3.2.jar
commons-lang-2.0.jar
commons-logging-1.0.4.jar
1 楼 hyneng 2012-05-04  
赞一个

相关推荐

Global site tag (gtag.js) - Google Analytics