Java操作MongoDB数据库示例分享
MongoDB是一个文档型数据库,是NOSQL家族中最重要的成员之一,以下代码封装了MongoDB的基本操作。
MongoDBConfig.java
packagecom.posoftframework.mongodb; importjava.io.File; importjava.io.FileInputStream; importjava.io.IOException; importjava.util.Enumeration; importjava.util.HashMap; importjava.util.Hashtable; importjava.util.List; importjava.util.Map; importjava.util.Properties; importcom.mongodb.DB; importcom.mongodb.Mongo; /** *MongoDB配置类 * *@authoryongtree *@date2010-7-7下午07:45:08 *@version1.0 */ publicclassMongoDBConfig{ privatestaticMongomongo; privatestaticDBdb; privatestaticfinalStringMONGO_DB_ADDRESS="localhost"; privatestaticfinalintMONGO_DB_PORT=27017; privatestaticfinalStringMONGO_DB_USERNAME="root"; privatestaticfinalStringMONGO_DB_PASSWORD="root"; privatestaticfinalStringMONGO_DB_DBNAME="mongodb"; privatestaticfinalStringMONGO_DB_RESOURCE_FILE="mongodb.cfg.properties"; /** *Mongo数据库参数 */ privatestaticMap<String,String>cfgMap=newHashMap<String,String>(); privatestaticHashtable<String,DB>mongoDBs=newHashtable<String,DB>(); /** *初始化Mongo的数据库 */ static{ init(); } publicstaticFilegetConfigFile(){ Stringpath=MongoDBConfig.class.getResource("/").getPath(); StringfileName=path+MONGO_DB_RESOURCE_FILE; Filefile=newFile(fileName); if(file.exists()){ returnfile; } returnnull; } @SuppressWarnings("unchecked") privatestaticvoidinitCfgMap(){ Filefile=getConfigFile(); if(file!=null){ Propertiesp=newProperties(); try{ p.load(newFileInputStream(file)); for(Enumerationenu=p.propertyNames();enu.hasMoreElements();){ Stringkey=(String)enu.nextElement(); Stringvalue=(String)p.getProperty(key); cfgMap.put(key,value); } }catch(IOExceptione){ System.out.println("记载Mongo配置文件失败!"); e.printStackTrace(); } }else{ cfgMap.put("mongo.db.address",MONGO_DB_ADDRESS); cfgMap.put("mongo.db.port",String.valueOf(MONGO_DB_PORT)); cfgMap.put("mongo.db.username",MONGO_DB_USERNAME); cfgMap.put("mongo.db.password",MONGO_DB_PASSWORD); cfgMap.put("mongo.db.dbname",MONGO_DB_DBNAME); } } /** *初始化Mongo数据库 */ privatestaticvoidinit(){ initCfgMap(); try{ Stringaddress=cfgMap.get("mongo.db.address"); intport=Integer.parseInt(cfgMap.get("mongo.db.port").toString()); StringdbName=cfgMap.get("mongo.db.dbname"); Stringusername=cfgMap.get("mongo.db.username"); Stringpassword=cfgMap.get("mongo.db.password"); mongo=newMongo(address,port); if(dbName!=null&&!"".equals(dbName)){ db=mongo.getDB(dbName); if(username!=null&&!"".equals(username)){ db.addUser(username,password.toCharArray()); } mongoDBs.put(dbName,db); } }catch(IOExceptione){ e.printStackTrace(); } } /** *得到Mongo的实例 * *@return */ publicstaticMongogetMongo(){ returnmongo; } /** *得到Mongo的图片数据库 * *@return */ publicstaticDBgetDB(){ returndb; } publicstaticList<String>getDBNames(){ returnmongo.getDatabaseNames(); } /** *根据数据库名称,得到数据库<br/> *如果不存在,则创建一个该名称的数据库,并设置用户名和密码为配置文件中的参数值</br> * *@paramdbName *@return */ publicstaticDBgetDBByName(StringdbName){ DBdb=mongo.getDB(dbName); if(!mongoDBs.contains(db)){ db.addUser(cfgMap.get("mongo.db.username"),cfgMap.get( "mongo.db.password").toCharArray()); mongoDBs.put(dbName,db); } returndb; } }
MongoService.java
/*************************版权声明********************************* ** *版权所有:百洋软件* *Copyright(c)2010bywww.po-soft.com* ** *************************变更记录********************************* * *创建者:yongtree创建日期:2010-7-7 *备注: * *修改者:修改日期: *备注: * */ packagecom.posoftframework.mongodb; importjava.util.List; importjava.util.Map; importcom.mongodb.DB; importcom.mongodb.DBCollection; importcom.mongodb.DBObject; /** *操作MongoDB的DAO接口 * *@authoryongtree *@date2010-7-7下午04:44:43 *@version1.0 */ publicinterfaceMongoService{ publicabstractDBCollectiongetCollection(); /** *根据数据集合的Map,插入数据map的key对应数据库中的DBCollection的key值 * *@paramobj */ publicabstractDBObjectinsert(DBObjectobj); /** *根据List<Map<String,Object>>结构的数据集合,插入数据 * *@paramlist */ publicabstractvoidinsertBatch(List<DBObject>list); /** *按照条件参数集合map,删除数据 * *@parammap */ publicabstractvoiddelete(DBObjectobj); /** *按照多种条件的并集,批量删除数据 * *@paramlist */ publicabstractvoiddeleteBatch(List<DBObject>list); /** *得到Collection()总的记录数 * *@return */ publicabstractlonggetCollectionCount(); publicabstractlonggetCount(DBObjectquery); publicabstractList<DBObject>find(DBObjectquery); publicabstractList<DBObject>find(DBObjectquery,DBObjectsort); publicabstractList<DBObject>find(DBObjectquery,DBObjectsort,intstart,intlimit); /** *根据whereFields参数,更新setFields值 * *@paramsetFields *@paramwhereFields */ publicabstractvoidupdate(DBObjectsetFields, DBObjectwhereFields); publicabstractList<DBObject>findAll(); /** *根据ID找到唯一数据有1个id字段标记 * *@paramid *@return */ publicabstractDBObjectgetById(Stringid); /** *获取所有数据库名称 * *@return */ publicList<String>getAllDBNames(); publicabstractStringgetDbName(); publicabstractvoidsetDbName(StringdbName); publicabstractDBgetDb(); publicabstractStringgetCollName(); publicabstractvoidsetCollName(StringcollName); }
MongoServiceImpl.java
/*************************版权声明********************************* ** *版权所有:百洋软件* *Copyright(c)2010bywww.po-soft.com* ** *************************变更记录********************************* * *创建者:yongtree创建日期:2010-7-7 *备注: * *修改者:修改日期: *备注: * */ packagecom.posoftframework.mongodb; importjava.util.ArrayList; importjava.util.List; importjava.util.Map; importorg.bson.types.ObjectId; importcom.mongodb.BasicDBObject; importcom.mongodb.DB; importcom.mongodb.DBCollection; importcom.mongodb.DBCursor; importcom.mongodb.DBObject; /** * *@authoryongtree *@date2010-7-7下午07:22:15 *@version1.0 */ publicclassMongoServiceImplimplementsMongoService{ privateStringdbName; privateStringcollName; privateDBdb; publicMongoServiceImpl(StringdbName,StringcollName){ this.dbName=dbName; this.collName=collName; try{ db=MongoDBConfig.getDBByName(this.dbName); }catch(Throwablee){ e.printStackTrace(); } } publicMongoServiceImpl(){ getDb(); } publicDBCollectiongetCollection(){ returndb.getCollection(this.collName); } publicDBObjectmap2Obj(Map<String,Object>map){ DBObjectobj=newBasicDBObject(); if(map.containsKey("class")&&map.get("class")instanceofClass) map.remove("class"); obj.putAll(map); returnobj; } publicDBObjectinsert(DBObjectobj){ getCollection().insert(obj); returnobj; } publicvoidinsertBatch(List<DBObject>list){ if(list==null||list.isEmpty()){ return; } List<DBObject>listDB=newArrayList<DBObject>(); for(inti=0;i<list.size();i++){ listDB.add(list.get(i)); } getCollection().insert(listDB); } publicvoiddelete(DBObjectobj){ getCollection().remove(obj); } publicvoiddeleteBatch(List<DBObject>list){ if(list==null||list.isEmpty()){ return; } for(inti=0;i<list.size();i++){ getCollection().remove(list.get(i)); } } publiclonggetCollectionCount(){ returngetCollection().getCount(); } publiclonggetCount(DBObjectobj){ if(obj!=null) returngetCollection().getCount(obj); returngetCollectionCount(); } publicList<DBObject>find(DBObjectobj){ DBCursorcur=getCollection().find(obj); returnDBCursor2list(cur); } @Override publicList<DBObject>find(DBObjectquery,DBObjectsort){ DBCursorcur; if(query!=null){ cur=getCollection().find(query); }else{ cur=getCollection().find(); } if(sort!=null){ cur.sort(sort); } returnDBCursor2list(cur); } @Override publicList<DBObject>find(DBObjectquery,DBObjectsort,intstart, intlimit){ DBCursorcur; if(query!=null){ cur=getCollection().find(query); }else{ cur=getCollection().find(); } if(sort!=null){ cur.sort(sort); } if(start==0){ cur.batchSize(limit); }else{ cur.skip(start).limit(limit); } returnDBCursor2list(cur); } privateList<DBObject>DBCursor2list(DBCursorcur){ List<DBObject>list=newArrayList<DBObject>(); if(cur!=null){ list=cur.toArray(); } returnlist; } publicvoidupdate(DBObjectsetFields,DBObjectwhereFields){ getCollection().updateMulti(setFields,whereFields); } publicList<DBObject>findAll(){ DBCursorcur=getCollection().find(); List<DBObject>list=newArrayList<DBObject>(); if(cur!=null){ list=cur.toArray(); } returnlist; } publicDBObjectgetById(Stringid){ DBObjectobj=newBasicDBObject(); obj.put("_id",newObjectId(id)); DBObjectresult=getCollection().findOne(obj); returnresult; } publicStringgetDbName(){ returndbName; } publicvoidsetDbName(StringdbName){ this.dbName=dbName; this.db=MongoDBConfig.getDBByName(this.dbName); } publicStringgetCollName(){ returncollName; } publicvoidsetCollName(StringcollName){ this.collName=collName; } publicDBgetDb(){ if(this.db==null){ if(this.dbName==null){ this.db=MongoDBConfig.getDB(); }else{ this.db=MongoDBConfig.getDBByName(this.dbName); } } returnthis.db; } publicList<String>getAllDBNames(){ returnMongoDBConfig.getDBNames(); } }