thomescai http://blog.csdn.net/thomescai(轉載請保留)
概要:實現用java封裝mongodb,解決了id自增和gridFS等問題。
/** * 資料庫介面 * @author thomescai@163.com * @version 2011-9-27 */public interface MongoService {/** * 通過gridFS上傳對象 * @param obj 目標對象 * @param paramsMap 參數map * @return * @throws Exception */public boolean gridFSUpload(Object obj, HashMap<String, Object> paramsMap)throws Exception;/** * 通過gridFS刪除 * @param paramsMap 參數map * @return */public boolean gridFSDelete(HashMap<String, Object> paramsMap);/** * 插入DBObject對象 * @param idName 該對象的Id名稱 * @param dbObject 該對象 * @return */public DBObject insert(String idName, DBObject dbObject);/** * 擷取對象 * @param dbObject * @return */public DBObject getByObj(DBObject dbObject);/** * 更新資料 * @param query 該資料的對象 * @param obj 更新的資料 * @return */public Boolean update(DBObject query,DBObject obj);/** * 刪除對象 * @param obj */public void remove(DBObject obj);}
public class MongoServiceImpl implements MongoService {private String bucketName;private DB db;public MongoServiceImpl(String dbName, String bucketName) {this.bucketName = bucketName;Mongo mongo;try {mongo = new Mongo("192.168.17.28", 27017);this.db = mongo.getDB(dbName);} catch (UnknownHostException e) {e.printStackTrace();} catch (MongoException e) {e.printStackTrace();}}/** * 通過gridFS上傳對象 * @param obj 目標對象 * @param paramsMap 參數map * @return * @throws Exception */@Overridepublic synchronized boolean gridFSUpload(Object obj, HashMap<String, Object> paramsMap)throws IOException {boolean flag = false;GridFS gridFS = new GridFS(db, bucketName);GridFSFile gridFSFile = null;if (obj instanceof InputStream) {gridFSFile = gridFS.createFile((InputStream) obj);} else if (obj instanceof byte[]) {gridFSFile = gridFS.createFile((byte[]) obj);} else if (obj instanceof File) {gridFSFile = gridFS.createFile((File) obj);}if (gridFSFile != null && paramsMap != null) {Iterator iter = paramsMap.entrySet().iterator();while (iter.hasNext()) {Map.Entry<String, Object> entry = (Entry<String, Object>) iter.next();gridFSFile.put(entry.getKey(), entry.getValue());}gridFSFile.save();flag = true;}return flag;}/** * 通過gridFS刪除 * @param paramsMap 參數map * @return */@Overridepublic synchronized boolean gridFSDelete(HashMap<String, Object> paramsMap) {boolean flag = false;GridFS gridFS = new GridFS(db, bucketName);DBObject query = new BasicDBObject();if (paramsMap != null) {Iterator iter = paramsMap.entrySet().iterator();while (iter.hasNext()) {Map.Entry<String, Object> entry = (Entry<String, Object>) iter.next();query.put(entry.getKey(), entry.getValue());}}DBObject obj = gridFS.findOne(query);if(obj != null){gridFS.remove(obj);flag = true;}return flag;}/** * 插入DBObject對象 * @param idName 該對象的Id名稱 * @param dbObject 該對象 * @return */@Overridepublic synchronized DBObject insert(String idName, DBObject dbObject) {Integer id = getAutoIncreaseID(idName);dbObject.put(idName, id);getCollection().insert(dbObject);return dbObject;}/** * 擷取串連 * @return */public DBCollection getCollection() {return db.getCollection(this.bucketName);}/** * 根據表名擷取串連 * @param name * @return */public DBCollection getCollection(String name) {return db.getCollection(name);}/** * 自增Id * @param idName 自增Id名稱 * @return Id */public Integer getAutoIncreaseID(String idName) {BasicDBObject query = new BasicDBObject();query.put("name", idName);BasicDBObject update = new BasicDBObject();update.put("$inc", new BasicDBObject("id", 1));DBObject dbObject2 = getCollection("inc_ids").findAndModify(query,null, null, false, update, true, true);Integer id = (Integer) dbObject2.get("id");return id;}/** * 擷取對象 * @param dbObject * @return */@Overridepublic synchronized DBObject getByObj(DBObject dbObject) {return getCollection().findOne(dbObject);}/** * 更新資料 * @param query 該資料的對象 * @param obj 更新的資料 * @return */@Overridepublic synchronized Boolean update(DBObject query,DBObject obj) {WriteResult rs = getCollection().update(query, obj);return (Boolean) rs.getField("updatedExisting");}@Overridepublic void remove(DBObject obj) {WriteResult result = getCollection().remove(obj);}}
public class Test {public static void main(String[] args) {MongoService userDAO = new MongoServiceImpl("account", "test");System.out.println("=============insert===============");DBObject obj = new BasicDBObject();obj.put("name", "aaa");obj = userDAO.insert("test_id", obj);System.out.println("=============get===============");DBObject objGet = new BasicDBObject();objGet.put("name", "aaa");objGet = userDAO.getByObj(objGet);System.out.println("=============set===============");DBObject objAdd = new BasicDBObject();objAdd.put("age2", "ag2444");userDAO.update(obj, new BasicDBObject("$set", objAdd));System.out.println("=============集合===============");DBObject objArrays = new BasicDBObject();objArrays.put("arrays", new BasicDBObject("array1", "111"));userDAO.update(obj, new BasicDBObject("$push", objArrays));//userDAO.remove(new BasicDBObject("test_id", 1));}}
運行結果:
表test:
表inc_ids:
說明:
1.在inc_ids中記錄各個表的id。每次執行
DBObject dbObject2 = getCollection("inc_ids").findAndModify(query,null, null, false, update, true, true);
實現id++。在這裡保留了mongodb內建的ObjectId,也可以用test_id直接替換_id。
2.僅對update做了簡單的封裝。update還有4種方法:
這4種方法是對db.collection.update( criteria, objNew, upsert, multi )做了擴充。說明如下:
criteria : update的查詢條件,類似sql update查詢內where後面的
objNew : update的對象和一些更新的操作符(如$,$inc...)等,也可以理解為sql update查詢內set後面的
upsert : 這個參數的意思是,如果不存在update的記錄,是否插入objNew,true為插入,預設是false,不插入。
multi : mongodb預設是false,只更新找到的第一條記錄,如果這個參數為true,就把按條件查出來多條記錄全部更新。
3.$push,$set等通過BasicDBObject對象的形式實現,如下:
DBObject objAdd = new BasicDBObject();objAdd.put("age2", "ag2444");userDAO.update(obj, new BasicDBObject("$set", objAdd));
userDAO.update(obj, new BasicDBObject("$push", objArrays));
可同樣適用在其他的命令。
參考資料:
http://hi.baidu.com/farmerluo/blog/item/9a23cb13a819bb2fdd540188.html——《MongoDB
update資料文法》
http://www.kafka0102.com/2011/03/435.html——《理解mongodb的ObjectId》