自定义的连接MongoDB的工具类(DBHelper)



你需要使用MongoDB的时候,必须要有个连接数据库的工具类.下面就是我自定义的DBHelper类


<span style="font-size:18px;">package com.yc.voting.dao;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.mongodb.BasicDBObject;
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.WriteResult;

public class DBHelper {
	private static Mongo mongo=null;
	private DB db=null;
	private DBCollection collection=null;

	static{
		try {
			mongo=new Mongo(MyPro.getInstance().getProperty("ip"),Integer.parseInt(MyPro.getInstance().getProperty("port")));
			System.out.println(mongo);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (MongoException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 连接数据库
	 * @param dbName:要链接的库
	 * @param name:用户名
	 * @param pwd:密码
	 * @return
	 */
	public boolean getDB(String dbName,String name,String pwd){
		db=mongo.getDB(dbName);
		if(name!=null && !"".equals(name) && pwd!=null && !"".equals(pwd)){
			if(db.authenticate(name, pwd.toCharArray())){
				return true;
			}else{
				return false;
			}
		}else{ //查看配置文件中是否给定用户名和密码
			String uname=MyPro.getInstance().getProperty("uname");
			String pwds=MyPro.getInstance().getProperty("password");
			
			if(uname!=null && !"".equals(uname) && pwds!=null && !"".equals(pwds)){
				if(db.authenticate(name, pwd.toCharArray())){
					return true;
				}else{
					return false;
				}
			}
		}
		return true;
	}
	
	/**
	 * 关闭连接
	 * @param mongo
	 */
	public void closeAll(DB db){
		if(db!=null){
			db.requestDone();
		}
	}
	
	/**
	 * 获取指定的集合
	 * @param collectionName:要连接的集合
	 * @return
	 */
	public DBCollection getDBCollection(String collectionName){
		DBCollection dbCollection=null;
		String dbName=MyPro.getInstance().getProperty("dbName");
		if(getDB(dbName,null,null)){
			db.requestStart();
			if(collectionName==null){ //如果为空则从配置文件中查找
				collectionName=MyPro.getInstance().getProperty("collectionName");
			}
			dbCollection=db.getCollection(collectionName);
		}else{
			//抛出一个异常
			throw new RuntimeException("数据库连接失败....");
		}
		return dbCollection;
	}
	
	/**
	 * 获取指定的集合
	 * @param collectionName:要连接的集合
	 * @param dbName:集合所在的数据库
	 * @return
	 */
	public DBCollection getDBCollection(String collectionName,String dbName){
		DBCollection dbCollection=null;
		if(getDB(dbName,null,null)){
			db.requestStart();
			if(collectionName==null){ //如果为空则从配置文件中查找
				collectionName=MyPro.getInstance().getProperty("collectionName");
			}
			dbCollection=db.getCollection(collectionName);
		}else{
			//抛出一个异常
			throw new RuntimeException("数据库连接失败....");
		}
		return dbCollection;
	}
	
	/**
	 * 获取指定的集合
	 * @param collectionName:要连接的集合
	 * @param dbName:集合所在的数据库
	 * @param name:连接数据的用户名
	 * @param password:连接数据库的密码
	 * @return
	 */
	public DBCollection getDBCollection(String collectionName,String dbName,String name,String password){
		DBCollection dbCollection=null;
		if(getDB(dbName,name,password)){
			db.requestStart();
			if(collectionName==null){ //如果为空则从配置文件中查找
				collectionName=MyPro.getInstance().getProperty("collectionName");
			}
			dbCollection=db.getCollection(collectionName);
		}else{
			//抛出一个异常
			throw new RuntimeException("数据库连接失败....");
		}
		return dbCollection;
	}
	
	/**
	 * 添加对象
	 * @param map:要添加的对象信息
	 * @param collectionName:集合
	 * @return
	 */
	public int addObject(Map<String,Object> map,String collectionName){
		WriteResult result=null;
		try {
			if(collectionName==null){
				collection=this.getDBCollection(null);
			}else{
				collection=this.getDBCollection(collectionName);
			}
			
			result=collection.save( new BasicDBObject(map));
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			this.closeAll(db);
		}
		return result.getN();
	}
	
	public int addObjects(Map<String,String> map,String collectionName){
		WriteResult result=null;
		try {
			if(collectionName==null){
				collection=this.getDBCollection(null);
			}else{
				collection=this.getDBCollection(collectionName);
			}
			
			result=collection.save( new BasicDBObject(map));
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			this.closeAll(db);
		}
		return result.getN();
	}
	
	/**
	 * 查询单个对象
	 * @param params:查询条件
	 * @param collectionName:集合名称
	 * @return
	 */
	public Object findOneToObject(Map<String,Object> params,String collectionName){
		DBObject object=null;
		
		try {
			if(collectionName==null){
				collection=this.getDBCollection(null);
			}else{
				collection=this.getDBCollection(collectionName);
			}
			if(params==null){
				object=collection.findOne();
			}else{
				object=collection.findOne(new BasicDBObject(params));
			}
		} catch (MongoException e) {
			e.printStackTrace();
		} finally{
			this.closeAll(db);
		}
		return object;
	}
	
	public Object findOneToObjects(Map<String,String> params,String collectionName){
		DBObject object=null;
		
		try {
			if(collectionName==null){
				collection=this.getDBCollection(null);
			}else{
				collection=this.getDBCollection(collectionName);
			}
			if(params==null){
				object=collection.findOne();
			}else{
				object=collection.findOne(new BasicDBObject(params));
			}
		} catch (MongoException e) {
			e.printStackTrace();
		} finally{
			this.closeAll(db);
		}
		return object;
	}
	
	/**
	 * 查询对象
	 * @param params:查询条件
	 * @param collectionName:集合名称
	 * @return
	 */
	public List<Object> findToObject(Map<String,Object> params,String collectionName){
		List<Object> list=new ArrayList<Object>();
		
		try {
			if(collectionName==null){
				collection=this.getDBCollection(null);
			}else{
				collection=this.getDBCollection(collectionName);
			}
			
			DBCursor cursor=null;
			if(params==null){
				cursor=collection.find();
			}else{
				cursor=collection.find(new BasicDBObject(params));
			}
			
			//DBObject object=null;
			while( cursor.hasNext() ){
				list.add(cursor.next());
			}
		} catch (MongoException e) {
			e.printStackTrace();
		} finally{
			this.closeAll(db);
		}
		return list;
	}
}
</span>

MyPro类 

<span style="font-size:18px;">package com.yc.voting.dao;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@SuppressWarnings("serial")
public class MyPro extends Properties {
	private static MyPro instance=new MyPro();
	
	private MyPro(){
		InputStream is=MyPro.class .getResourceAsStream("/db.properties");
		try {
			this.load(is);
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static MyPro getInstance(){
		return instance;
	}
}
</span>

db.properties

<span style="font-size:18px;">#数据库所在的地址
ip=127.0.0.1

#端口号
port=27017

#要连接的数据库
dbName=yc

#用户名
uname=

#密码
password=

#默认连接的集合
collectionName=yc</span>



你需要使用MongoDB的时候,必须要有个连接数据库的工具类.下面就是我自定义的DBHelper类


<span style="font-size:18px;">package com.yc.voting.dao;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.mongodb.BasicDBObject;
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.WriteResult;

public class DBHelper {
	private static Mongo mongo=null;
	private DB db=null;
	private DBCollection collection=null;

	static{
		try {
			mongo=new Mongo(MyPro.getInstance().getProperty("ip"),Integer.parseInt(MyPro.getInstance().getProperty("port")));
			System.out.println(mongo);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (MongoException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 连接数据库
	 * @param dbName:要链接的库
	 * @param name:用户名
	 * @param pwd:密码
	 * @return
	 */
	public boolean getDB(String dbName,String name,String pwd){
		db=mongo.getDB(dbName);
		if(name!=null && !"".equals(name) && pwd!=null && !"".equals(pwd)){
			if(db.authenticate(name, pwd.toCharArray())){
				return true;
			}else{
				return false;
			}
		}else{ //查看配置文件中是否给定用户名和密码
			String uname=MyPro.getInstance().getProperty("uname");
			String pwds=MyPro.getInstance().getProperty("password");
			
			if(uname!=null && !"".equals(uname) && pwds!=null && !"".equals(pwds)){
				if(db.authenticate(name, pwd.toCharArray())){
					return true;
				}else{
					return false;
				}
			}
		}
		return true;
	}
	
	/**
	 * 关闭连接
	 * @param mongo
	 */
	public void closeAll(DB db){
		if(db!=null){
			db.requestDone();
		}
	}
	
	/**
	 * 获取指定的集合
	 * @param collectionName:要连接的集合
	 * @return
	 */
	public DBCollection getDBCollection(String collectionName){
		DBCollection dbCollection=null;
		String dbName=MyPro.getInstance().getProperty("dbName");
		if(getDB(dbName,null,null)){
			db.requestStart();
			if(collectionName==null){ //如果为空则从配置文件中查找
				collectionName=MyPro.getInstance().getProperty("collectionName");
			}
			dbCollection=db.getCollection(collectionName);
		}else{
			//抛出一个异常
			throw new RuntimeException("数据库连接失败....");
		}
		return dbCollection;
	}
	
	/**
	 * 获取指定的集合
	 * @param collectionName:要连接的集合
	 * @param dbName:集合所在的数据库
	 * @return
	 */
	public DBCollection getDBCollection(String collectionName,String dbName){
		DBCollection dbCollection=null;
		if(getDB(dbName,null,null)){
			db.requestStart();
			if(collectionName==null){ //如果为空则从配置文件中查找
				collectionName=MyPro.getInstance().getProperty("collectionName");
			}
			dbCollection=db.getCollection(collectionName);
		}else{
			//抛出一个异常
			throw new RuntimeException("数据库连接失败....");
		}
		return dbCollection;
	}
	
	/**
	 * 获取指定的集合
	 * @param collectionName:要连接的集合
	 * @param dbName:集合所在的数据库
	 * @param name:连接数据的用户名
	 * @param password:连接数据库的密码
	 * @return
	 */
	public DBCollection getDBCollection(String collectionName,String dbName,String name,String password){
		DBCollection dbCollection=null;
		if(getDB(dbName,name,password)){
			db.requestStart();
			if(collectionName==null){ //如果为空则从配置文件中查找
				collectionName=MyPro.getInstance().getProperty("collectionName");
			}
			dbCollection=db.getCollection(collectionName);
		}else{
			//抛出一个异常
			throw new RuntimeException("数据库连接失败....");
		}
		return dbCollection;
	}
	
	/**
	 * 添加对象
	 * @param map:要添加的对象信息
	 * @param collectionName:集合
	 * @return
	 */
	public int addObject(Map<String,Object> map,String collectionName){
		WriteResult result=null;
		try {
			if(collectionName==null){
				collection=this.getDBCollection(null);
			}else{
				collection=this.getDBCollection(collectionName);
			}
			
			result=collection.save( new BasicDBObject(map));
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			this.closeAll(db);
		}
		return result.getN();
	}
	
	public int addObjects(Map<String,String> map,String collectionName){
		WriteResult result=null;
		try {
			if(collectionName==null){
				collection=this.getDBCollection(null);
			}else{
				collection=this.getDBCollection(collectionName);
			}
			
			result=collection.save( new BasicDBObject(map));
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			this.closeAll(db);
		}
		return result.getN();
	}
	
	/**
	 * 查询单个对象
	 * @param params:查询条件
	 * @param collectionName:集合名称
	 * @return
	 */
	public Object findOneToObject(Map<String,Object> params,String collectionName){
		DBObject object=null;
		
		try {
			if(collectionName==null){
				collection=this.getDBCollection(null);
			}else{
				collection=this.getDBCollection(collectionName);
			}
			if(params==null){
				object=collection.findOne();
			}else{
				object=collection.findOne(new BasicDBObject(params));
			}
		} catch (MongoException e) {
			e.printStackTrace();
		} finally{
			this.closeAll(db);
		}
		return object;
	}
	
	public Object findOneToObjects(Map<String,String> params,String collectionName){
		DBObject object=null;
		
		try {
			if(collectionName==null){
				collection=this.getDBCollection(null);
			}else{
				collection=this.getDBCollection(collectionName);
			}
			if(params==null){
				object=collection.findOne();
			}else{
				object=collection.findOne(new BasicDBObject(params));
			}
		} catch (MongoException e) {
			e.printStackTrace();
		} finally{
			this.closeAll(db);
		}
		return object;
	}
	
	/**
	 * 查询对象
	 * @param params:查询条件
	 * @param collectionName:集合名称
	 * @return
	 */
	public List<Object> findToObject(Map<String,Object> params,String collectionName){
		List<Object> list=new ArrayList<Object>();
		
		try {
			if(collectionName==null){
				collection=this.getDBCollection(null);
			}else{
				collection=this.getDBCollection(collectionName);
			}
			
			DBCursor cursor=null;
			if(params==null){
				cursor=collection.find();
			}else{
				cursor=collection.find(new BasicDBObject(params));
			}
			
			//DBObject object=null;
			while( cursor.hasNext() ){
				list.add(cursor.next());
			}
		} catch (MongoException e) {
			e.printStackTrace();
		} finally{
			this.closeAll(db);
		}
		return list;
	}
}
</span>

MyPro类 

<span style="font-size:18px;">package com.yc.voting.dao;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@SuppressWarnings("serial")
public class MyPro extends Properties {
	private static MyPro instance=new MyPro();
	
	private MyPro(){
		InputStream is=MyPro.class .getResourceAsStream("/db.properties");
		try {
			this.load(is);
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static MyPro getInstance(){
		return instance;
	}
}
</span>

db.properties

<span style="font-size:18px;">#数据库所在的地址
ip=127.0.0.1

#端口号
port=27017

#要连接的数据库
dbName=yc

#用户名
uname=

#密码
password=

#默认连接的集合
collectionName=yc</span>



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值