mongodb——java封装(id自增,gridFS)

http://blog.csdn.net/thomescai/article/details/6829771

 thomescai http://blog.csdn.net/thomescai(转载请保留)

概要:实现用java封装mongodb,解决了id自增和gridFS等问题。


[html]  view plain copy
  1. /**  
  2.  * 数据库接口  
  3.  * @author [email protected]  
  4.  * @version 2011-9-27  
  5.  */  
  6. public interface MongoService {  
  7.   
  8.     /**  
  9.      * 通过gridFS上传对象  
  10.      * @param obj 目标对象  
  11.      * @param paramsMap 参数map  
  12.      * @return  
  13.      * @throws Exception  
  14.      */  
  15.     public  boolean gridFSUpload(Object obj, HashMap<String, Object> paramsMap)  
  16.             throws Exception;  
  17.   
  18.     /**  
  19.      * 通过gridFS删除  
  20.      * @param paramsMap 参数map  
  21.      * @return  
  22.      */  
  23.     public boolean gridFSDelete(HashMap<String, Object> paramsMap);  
  24.   
  25.     /**  
  26.      * 插入DBObject对象  
  27.      * @param idName 该对象的Id名称  
  28.      * @param dbObject 该对象  
  29.      * @return  
  30.      */  
  31.     public DBObject insert(String idName, DBObject dbObject);  
  32.   
  33.     /**  
  34.      * 获取对象  
  35.      * @param dbObject   
  36.      * @return  
  37.      */  
  38.     public DBObject getByObj(DBObject dbObject);  
  39.       
  40.     /**  
  41.      * 更新数据  
  42.      * @param query 该数据的对象  
  43.      * @param obj 更新的数据  
  44.      * @return   
  45.      */  
  46.     public Boolean update(DBObject query,DBObject obj);  
  47.       
  48.       
  49.     /**  
  50.      * 删除对象  
  51.      * @param obj  
  52.      */  
  53.     public void remove(DBObject obj);  
  54. }  

[html]  view plain copy
  1. public class MongoServiceImpl implements MongoService {  
  2.   
  3.     private String bucketName;  
  4.     private DB db;  
  5.   
  6.     public MongoServiceImpl(String dbName, String bucketName) {  
  7.         this.bucketName = bucketName;  
  8.         Mongo mongo;  
  9.         try {  
  10.             mongo = new Mongo("192.168.17.28", 27017);  
  11.             this.db = mongo.getDB(dbName);  
  12.         } catch (UnknownHostException e) {  
  13.             e.printStackTrace();  
  14.         } catch (MongoException e) {  
  15.             e.printStackTrace();  
  16.         }  
  17.     }  
  18.   
  19.     /**  
  20.      * 通过gridFS上传对象  
  21.      * @param obj 目标对象  
  22.      * @param paramsMap 参数map  
  23.      * @return  
  24.      * @throws Exception  
  25.      */  
  26.     @Override  
  27.     public synchronized boolean gridFSUpload(Object obj, HashMap<String, Object> paramsMap)  
  28.             throws IOException {  
  29.         boolean flag = false;  
  30.   
  31.         GridFS gridFS = new GridFS(db, bucketName);  
  32.           
  33.         GridFSFile gridFSFile = null;  
  34.         if (obj instanceof InputStream) {  
  35.             gridFSFile = gridFS.createFile((InputStream) obj);  
  36.         } else if (obj instanceof byte[]) {  
  37.             gridFSFile = gridFS.createFile((byte[]) obj);  
  38.         } else if (obj instanceof File) {  
  39.             gridFSFile = gridFS.createFile((File) obj);  
  40.         }  
  41.         if (gridFSFile != null && paramsMap != null) {  
  42.             Iterator iter = paramsMap.entrySet().iterator();  
  43.             while (iter.hasNext()) {  
  44.                 Map.Entry<String, Object> entry = (Entry<String, Object>) iter.next();  
  45.                 gridFSFile.put(entry.getKey(), entry.getValue());  
  46.             }  
  47.             gridFSFile.save();  
  48.             flag = true;  
  49.         }  
  50.         return flag;  
  51.     }  
  52.   
  53.     /**  
  54.      * 通过gridFS删除  
  55.      * @param paramsMap 参数map  
  56.      * @return  
  57.      */  
  58.     @Override  
  59.     public synchronized boolean gridFSDelete(HashMap<String, Object> paramsMap) {  
  60.         boolean flag = false;  
  61.         GridFS gridFS = new GridFS(db, bucketName);  
  62.         DBObject query = new BasicDBObject();  
  63.         if (paramsMap != null) {  
  64.             Iterator iter = paramsMap.entrySet().iterator();  
  65.             while (iter.hasNext()) {  
  66.                 Map.Entry<String, Object> entry = (Entry<String, Object>) iter.next();  
  67.                 query.put(entry.getKey(), entry.getValue());  
  68.             }  
  69.         }  
  70.         DBObject obj = gridFS.findOne(query);  
  71.         if(obj != null){  
  72.             gridFS.remove(obj);  
  73.             flag = true;  
  74.         }  
  75.         return flag;  
  76.     }  
  77.   
  78.     /**  
  79.      * 插入DBObject对象  
  80.      * @param idName 该对象的Id名称  
  81.      * @param dbObject 该对象  
  82.      * @return  
  83.      */  
  84.     @Override  
  85.     public synchronized DBObject insert(String idName, DBObject dbObject) {  
  86.         Integer id = getAutoIncreaseID(idName);  
  87.         dbObject.put(idName, id);  
  88.         getCollection().insert(dbObject);  
  89.         return dbObject;  
  90.     }  
  91.   
  92.     /**  
  93.      * 获取连接  
  94.      * @return   
  95.      */  
  96.     public DBCollection getCollection() {  
  97.         return db.getCollection(this.bucketName);  
  98.     }  
  99.   
  100.     /**  
  101.      * 根据表名获取连接  
  102.      * @param name   
  103.      * @return  
  104.      */  
  105.     public DBCollection getCollection(String name) {  
  106.         return db.getCollection(name);  
  107.     }  
  108.   
  109.     /**  
  110.      * 自增Id  
  111.      * @param idName 自增Id名称  
  112.      * @return Id  
  113.      */  
  114.     public Integer getAutoIncreaseID(String idName) {  
  115.         BasicDBObject query = new BasicDBObject();  
  116.         query.put("name", idName);  
  117.   
  118.         BasicDBObject update = new BasicDBObject();  
  119.         update.put("$inc", new BasicDBObject("id", 1));  
  120.   
  121.         DBObject dbObject2 = getCollection("inc_ids").findAndModify(query,  
  122.                 null, null, false, update, true, true);  
  123.           
  124.         Integer id = (Integer) dbObject2.get("id");  
  125.         return id;  
  126.     }  
  127.       
  128.     /**  
  129.      * 获取对象  
  130.      * @param dbObject   
  131.      * @return  
  132.      */  
  133.     @Override  
  134.     public synchronized DBObject getByObj(DBObject dbObject) {  
  135.         return getCollection().findOne(dbObject);  
  136.     }  
  137.       
  138.     /**  
  139.      * 更新数据  
  140.      * @param query 该数据的对象  
  141.      * @param obj 更新的数据  
  142.      * @return   
  143.      */  
  144.     @Override  
  145.     public synchronized Boolean update(DBObject query,DBObject obj) {  
  146.         WriteResult rs = getCollection().update(query, obj);  
  147.         return (Boolean) rs.getField("updatedExisting");  
  148.     }  
  149.   
  150.       
  151.   
  152.     @Override  
  153.     public void remove(DBObject obj) {  
  154.         WriteResult result = getCollection().remove(obj);  
  155.     }  
  156. }  

[html]  view plain copy
  1. public class Test {  
  2.       
  3.     public static void main(String[] args) {  
  4.         MongoService userDAO = new MongoServiceImpl("account", "test");  
  5.   
  6.         System.out.println("=============insert===============");  
  7.         DBObject obj = new BasicDBObject();  
  8.         obj.put("name", "aaa");  
  9.         obj = userDAO.insert("test_id", obj);  
  10.   
  11.         System.out.println("=============get===============");  
  12.         DBObject objGet = new BasicDBObject();  
  13.         objGet.put("name", "aaa");  
  14.         objGet = userDAO.getByObj(objGet);  
  15.   
  16.         System.out.println("=============set===============");  
  17.         DBObject objAdd = new BasicDBObject();  
  18.         objAdd.put("age2", "ag2444");  
  19.   
  20.         userDAO.update(obj, new BasicDBObject("$set", objAdd));  
  21.   
  22.         System.out.println("=============集合===============");  
  23.         DBObject objArrays = new BasicDBObject();  
  24.         objArrays.put("arrays", new BasicDBObject("array1", "111"));  
  25.   
  26.         userDAO.update(obj, new BasicDBObject("$push", objArrays));  
  27.           
  28.           
  29. //      userDAO.remove(new BasicDBObject("test_id", 1));  
  30.     }  
  31. }  
运行结果:

表test:
mongodb——java封装(id自增,gridFS)_第1张图片

表inc_ids:

mongodb——java封装(id自增,gridFS)_第2张图片

说明:

    1.在inc_ids中记录各个表的id。每次执行

[html]  view plain copy
  1. DBObject dbObject2 = getCollection("inc_ids").findAndModify(query,  
  2.                 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对象的形式实现,如下:

[html]  view plain copy
  1. DBObject objAdd = new BasicDBObject();  
  2. objAdd.put("age2", "ag2444");  
  3. userDAO.update(obj, new BasicDBObject("$set", objAdd));  
[html]  view plain copy
  1. 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》


你可能感兴趣的:(mongodb——java封装(id自增,gridFS))