http://blog.csdn.net/thomescai/article/details/6829771
thomescai http://blog.csdn.net/thomescai(转载请保留)
概要:实现用java封装mongodb,解决了id自增和gridFS等问题。
- /**
- * 数据库接口
- * @author [email protected]
- * @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
- */
- @Override
- public 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
- */
- @Override
- public 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
- */
- @Override
- public 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
- */
- @Override
- public synchronized DBObject getByObj(DBObject dbObject) {
- return getCollection().findOne(dbObject);
- }
-
- /**
- * 更新数据
- * @param query 该数据的对象
- * @param obj 更新的数据
- * @return
- */
- @Override
- public synchronized Boolean update(DBObject query,DBObject obj) {
- WriteResult rs = getCollection().update(query, obj);
- return (Boolean) rs.getField("updatedExisting");
- }
-
-
-
- @Override
- public 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》