首页 > 代码库 > MongoDB增删改查实例

MongoDB增删改查实例

MongoDB之Java测试代码(DAO层),mongodbdao


MongoInit.java是数据库初始化及连接类

MongoUtils.java是对mongodb的各种操作方法

MongoInit.java

package com.wlwcloud.datatest;  import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.UnknownHostException; import java.util.Properties;  import org.apache.log4j.Logger;  import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.Mongo; import com.mongodb.MongoOptions; import com.mongodb.ServerAddress;  /**  * Mongo工具类:设计为单例模式,每当月份发生变化,数据库连接名称就会发生变化,这是业务规则 因MongoDB的Java驱动是线程安全的,对于一般的应用,只要一个Mongo实例即可,Mongo有个内置的连接池(池大小默认为10个)。  * 对于有大量写和读的环境中,为了确保在一个Session中使用同一个DB时,我们可以用以下方式保证一致性: DB mdb =mongo.getDB(‘dbname‘); mdb.requestStart(); // 业务代码 mdb.requestDone();  * DB和DBCollection是绝对线程安全的  * @author undoner  */ public class MongoInit { 	/** DB监听端口号 */ 	private static int DBPort = 27017; 	/** DB连接URL */ 	private static String DBUrl = "localhost"; 	/** 连接DB库名称 */ 	private static String DBName = "wlwdb"; 	static Logger log = Logger.getRootLogger(); 	private static Mongo mongo; 	private static DBCollection coll; 	private static DB db;  	static { 		try { 			DBproperties(); 			MongoOptions options = new MongoOptions(); 			options.autoConnectRetry = true; 			options.connectionsPerHost = 1000; 			options.maxWaitTime = 5000; 			options.socketTimeout = 0; 			options.connectTimeout = 15000; 			options.threadsAllowedToBlockForConnectionMultiplier = 5000; 			// 事实上,Mongo实例代表了一个数据库连接池,即使在多线程的环境中,一个Mongo实例对我们来说已经足够了 			ServerAddress serverAddress = new ServerAddress(DBUrl, DBPort); 			mongo = new Mongo(serverAddress, options); 		} catch (UnknownHostException e) { 			log.info("get mongo instance failed"); 		} 	}  	static void DBproperties() { 		// 读取配置文件config.properties中的属性值 		String myFilePath = MongoInit.class.getResource("/").getPath() + "MongoDBConfig.properties"; 		Properties properties = new Properties(); 		FileInputStream fileInputStream = null; 		try { 			   fileInputStream = new FileInputStream(myFilePath); 			   properties.load(fileInputStream); 			   DBPort = Integer.parseInt((String) properties.getProperty("DBPort")); 			   DBUrl = (String) properties.getProperty("DBUrl"); 			   DBName = (String) properties.getProperty("DBName"); 			  } catch (Exception e) { 			   e.printStackTrace(); 			  } finally { 			   try { 			    fileInputStream.close(); 			   } catch (IOException e) { 			    // TODO Auto-generated catch block 			    e.printStackTrace(); 			   } 		}  	}  	public static DB getDB() { 		if (db == null) { 			db = mongo.getDB(DBName); 		} 		return db; 	}  	public static Mongo getMong() { 		return mongo; 	}  	public static DBCollection getColl(String collname) { 		return getDB().getCollection(collname); 	}  }

MongoUtils.java

package com.wlwcloud.datatest;  import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; import java.util.regex.Pattern;  import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.ketayao.ketacustom.entity.main.User; import com.ketayao.utils.SecurityUtils; import com.mongodb.AggregationOutput; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObjectBuilder; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MapReduceCommand; import com.mongodb.MapReduceOutput; import com.mongodb.Mongo; import com.mongodb.MongoException; import com.mongodb.QueryBuilder; import com.mongodb.WriteConcern;  public class MongoUtils { 	//DBCursor cursor = coll.find(condition).addOption(Bytes.QUERYOPTION_NOTIMEOUT);//设置游标不要超时             /**       * 获取所有数据库实例       */       public void testGetDBS() {           List<String> dbnames = MongoInit.getMong().getDatabaseNames();           for (String dbname : dbnames) {               System.out.println("dbname:" + dbname);           }       }                /**       * 删除数据库       */       public void dropDatabase(String dbname) {           MongoInit.getMong().dropDatabase(dbname);       }                /**       * 查询所有表名       */       public void getAllCollections() {           Set<String> colls = MongoInit.getDB().getCollectionNames();           for (String s : colls) {               System.out.println("Collections:"+s);           }       }          /**       * 删除一个表       */       public void dropCollection(String collection) {           MongoInit.getColl(collection).drop();       }          /**       * 添加一条记录       */             public void addData(String dbCollection,String dataID,String dataTime,String dataContent,String dataStatus) {           DBCollection coll = MongoInit.getColl(dbCollection);           BasicDBObject doc = new BasicDBObject();           doc.put("id", dataID);           doc.put("time", dataTime);           doc.put("data", dataContent);           doc.put("status", dataStatus);           coll.insert(doc);           // 设定write concern,以便操作失败时得到提示           coll.setWriteConcern(WriteConcern.SAFE);           findOne(dbCollection);     }                /**       * 创建索引       */       public void createIndex(String collection) {           MongoInit.getColl(collection).createIndex(new BasicDBObject("index_id", 1));       }                /**       * 获取索引信息       */       public void getIndexInfo(String dbCollection) {           List<DBObject> list = MongoInit.getColl(dbCollection).getIndexInfo();           for (DBObject o : list) {               System.out.println(o);           }       }                /**       * 添加多条记录       */       public void addMultiData() {           for (int i = 0; i < 100; i++) {               MongoInit.getColl("wujintao").insert(                       new BasicDBObject().append("i", i));           }              List<DBObject> docs = new ArrayList<DBObject>();           for (int i = 0; i < 50; i++) {               docs.add(new BasicDBObject().append("i", i));           }           MongoInit.getColl("wujintao").insert(docs);           // 设定write concern,以便操作失败时得到提示           MongoInit.getColl("wujintao").setWriteConcern(WriteConcern.SAFE);       }                /**       * 查找第一条记录       */       public void findOne(String dbCollection) {           DBObject myDoc = MongoInit.getColl(dbCollection).findOne();           System.out.println(myDoc);       }                /**       * 获取表中所有记录条数       */       public void count(String dbCollection) {           System.out.println(MongoInit.getColl(dbCollection).getCount());           System.out.println(MongoInit.getColl(dbCollection).count());       }                /**       * 获取查询结果集的记录数       */       public void getCount(String dbCollection,String dataID) {           DBObject query = new BasicDBObject("id", dataID);           long count = MongoInit.getColl(dbCollection).count(query);           System.out.println(count);       }                /**       * 查询所有结果       */       public void getAllDocuments(String dbCollection) {           DBCursor cursor = MongoInit.getColl(dbCollection).find();           try {               while (cursor.hasNext()) {                   System.out.println(cursor.next());               }           } finally {               cursor.close();           }       }                /**       * 按照一个条件查询       */       public void queryByConditionOne() {           BasicDBObject query = new BasicDBObject();           query.put("name", "MongoDB");           DBCursor cursor = MongoInit.getColl("wujintao").find(query);              try {               while (cursor.hasNext()) {                   System.out.println(cursor.next());               }           } finally {               cursor.close();           }       }       public List<SensorData> queryById(String id) {      	User user = SecurityUtils.getLoginUser();         BasicDBObject query = new BasicDBObject();           System.out.print(id);         query.put("id", id);           String table="table_";         DBCursor cursor = MongoInit.getColl("table_"+user.getUsername()).find(query);           List<DBObject> list=cursor.toArray();         System.out.println(list.size());         System.out.println("dao.."+list.toString());         List<SensorData> sensordata=http://www.mamicode.com/new ArrayList();         for(int i=1;i(list.size()); 			 			ObjectMapper mapper = new ObjectMapper();   			String jsonfromList = null; 			try { 				//list转json 				jsonfromList = mapper.writeValueAsString(list); 			} catch (JsonProcessingException e) { 				// TODO Auto-generated catch block 				e.printStackTrace(); 			}   	        //System.out.println(jsonfromList);   //			for(int i=0;i
MongoDBConfig.properties

#端口设置 DBPort=27017 #URL DBUrl=localhost #URL DBName=wlwdb 



[DAO层]java代码解释逐行解释

你用的应该是ibatis,这里是批量删除,相当于把一堆操作用一个事务来提交,提高数据库性能。
//函数功能,删除list中的所有元素在数据库中的记录。
protected void batchDelete(List<?> lst, String statement)
throws SQLException
{
getSqlMapClient().startBatch();//开始批量操作
//遍历list
for (Iterator localIterator = lst.iterator(); localIterator.hasNext(); ) 

Object obj = localIterator.next();
getSqlMapClient().delete(statement, obj);//statement表示你调用的删除方法,在xml文件中定义的。
}
getSqlMapClient().executeBatch();//结束批量操作
}

MongoDB增删改查实例