`

mongodb初体验

阅读更多
package com.yt;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
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.yt.man.Man;
import com.yt.man.ManRepository;

@Controller
@RequestMapping("/test")
public class TestController {

	@Resource(name = "manRepo")
	private ManRepository manRepo;

	/**
	 * 删除
	 * @return
	 * @throws UnknownHostException
	 * @throws MongoException
	 */
	@RequestMapping(value = "/delete")
	public String index() throws UnknownHostException, MongoException {
		DBCollection coll = setConnect("stdent");
		coll.drop();
		return "";
	}
	
	/**
	 * 添加
	 * @return
	 * @throws UnknownHostException
	 * @throws MongoException
	 */
	@RequestMapping(value = "/insert")
	public String insert() throws UnknownHostException, MongoException {
		DBCollection coll = setConnect("stdent");
		//List<Man> manlist = manRepo.getManlistBysql(500, 1);
		List<Man> manlist = manRepo.getGqById();
		List<DBObject> datas = new ArrayList<DBObject>();
		for (int i = 0; i < manlist.size(); i++) {
			Man man = manlist.get(i);
			BasicDBObject doc = new BasicDBObject();
			doc.put("id", man.getId());
			doc.put("name", man.getName());
			doc.put("addr", man.getAddr());
			datas.add(doc);
		}
		coll.insert(datas);
		return "";
	}
	
	/**
	 * 查询
	 * @return
	 * @throws UnknownHostException
	 * @throws MongoException
	 */
	@RequestMapping(value = "/select")
	public String select() throws UnknownHostException, MongoException {
		DBCollection coll = setConnect("stdent");
		//DBCursor cursor = coll.find().limit(10).skip(10); 分页查询
		DBCursor cursor = coll.find();
		System.out.println("数量: "+cursor.count());
		for(Iterator<DBObject> it = cursor.iterator();it.hasNext();){
			DBObject o = (DBObject) it.next();
			System.out.println(o.get("id")+"  "+o.get("name")+"  "+ o.get("addr"));
		}
		return "";
	}
	
	public DBCollection setConnect(String tableName) throws UnknownHostException, MongoException{
		Mongo m = new Mongo("192.168.8.65", 27017);
		DB db = m.getDB("memo");
		DBCollection coll = db.getCollection(tableName);
		return coll;
	}
}
 

 

分享到:
评论
1 楼 静水深流 2011-08-26  
能不能把mongo20101101164410.rar里面的jar包给我发一份啊,自己去找太麻烦了,谢谢

相关推荐

Global site tag (gtag.js) - Google Analytics