免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 5730 | 回复: 1
打印 上一主题 下一主题

Java MongoDB封装 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-07-30 10:30 |只看该作者 |倒序浏览
驱动包版本最高是2.10.1
2.10.1以上版本中删除了ObjectId.massageToObjectId(key); 这个方法,
所以最高是2.10.1.
可以在 http://search.maven.org/ 中找到这个版本

配置文件只需在classpath下即可,名字任取,传参数即可.

MongoManager.java
  1. package com.liloo.db;

  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.concurrent.LinkedBlockingQueue;

  5. import org.apache.log4j.Logger;
  6. import org.bson.types.ObjectId;

  7. import com.liloo.util.SystemMessage;
  8. import com.mongodb.BasicDBObject;
  9. import com.mongodb.DB;
  10. import com.mongodb.DBCollection;
  11. import com.mongodb.DBCursor;
  12. import com.mongodb.DBObject;
  13. import com.mongodb.MongoClient;

  14. /**
  15. * @作者 Liloo
  16. * @E-mail liloo@vip.qq.com
  17. * @时间 2015年5月14日
  18. * @版权 © Liloo 版权所有.
  19. */
  20. public class MongoManager {

  21.     private static Logger log = Logger.getLogger(MongoManager.class);

  22.     private static final MongoManager instance = new MongoManager();

  23.     private static MongoClient mongo = null;
  24.      
  25.     private static final String  host = SystemMessage.getString("systemConstant", "mongo_host");
  26.     private static final Integer port = Integer.valueOf(SystemMessage.getString("systemConstant", "mongo_port"));
  27.      
  28.     /**
  29.      * 私有化
  30.      */
  31.     private MongoManager() {
  32.     }
  33.      
  34.     /**
  35.      * 单例
  36.      * @return
  37.      */
  38.     public static MongoManager getInstance() {
  39.          
  40.         return instance;
  41.          
  42.     }
  43.      
  44.     /**
  45.      * 初始化MongoDB
  46.      */
  47.     public void init() {

  48.         try {

  49.             mongo = new MongoClient(host, port);
  50.             log.info("MongoDB init success!");

  51.         } catch (Exception e) {
  52.             e.printStackTrace();
  53.         }
  54.          
  55.     }

  56.     /**
  57.      * 获取DB对象
  58.      * @return
  59.      */
  60.     public DB getDB() {
  61.          
  62.         try {
  63.             
  64.             if (mongo == null) {
  65.                  
  66.                 init();
  67.                 log.debug("Get DB : " + SystemMessage.getString("systemConstant", "DB_name"));
  68.                  
  69.             }
  70.             
  71.             return mongo.getDB(SystemMessage.getString("systemConstant", "DB_name"));
  72.             
  73.         } catch (Exception e) {
  74.             e.printStackTrace();
  75.         }
  76.          
  77.         return null;

  78.     }

  79.     /**
  80.      * 获取集合对象
  81.      * @param name
  82.      * @return
  83.      */
  84.     private DBCollection getCollection(String name) {
  85.          
  86.         try {
  87.             
  88.             return getDB().getCollection(name);
  89.             
  90.         } catch (Exception e) {
  91.             e.printStackTrace();
  92.         }

  93.         return null;

  94.     }

  95.     /**
  96.      * 插入MongoDB
  97.      * @param name
  98.      * @param obj
  99.      */
  100.     public void insert(String name, DBObject obj) {
  101.          
  102.         try {
  103.             
  104.             long begin = System.currentTimeMillis();
  105.             getCollection(name).insert(obj);
  106.             long end = System.currentTimeMillis();
  107.             log.debug("Insert Complete! Cost " + (end - begin) + "/ms");
  108.             
  109.         } catch (Exception e) {
  110.             e.printStackTrace();
  111.         }

  112.          
  113.     }

  114.     /**
  115.      * 删除指定条件的数据
  116.      * @param name
  117.      * @param obj
  118.      */
  119.     public void delete(String name, DBObject obj) {
  120.          
  121.         try {
  122.             
  123.             getCollection(name).remove(obj);
  124.             
  125.         } catch (Exception e) {
  126.             e.printStackTrace();
  127.         }

  128.     }

  129.     /**
  130.      * 清空集合
  131.      * @param collection
  132.      * @throws Exception
  133.      */
  134.     public void deleteAll(String collection) {

  135.         try {
  136.             
  137.             List<DBObject> rs = findAll(collection);
  138.          
  139.             if (rs != null && !rs.isEmpty()) {
  140.                  
  141.                 for (int i = 0; i < rs.size(); i++) {
  142.                     getCollection(collection).remove(rs.get(i));
  143.                 }
  144.                  
  145.             }
  146.          
  147.         } catch (Exception e) {
  148.             e.printStackTrace();
  149.         }
  150.          
  151.     }

  152.     /**
  153.      * 如果更新的数据 不存在 插入一条数据
  154.      * @param collection
  155.      * @param setFields
  156.      * @param whereFields
  157.      */
  158.     public void updateOrInsert(String name, DBObject set, DBObject where) {

  159.         try {
  160.             
  161.             getCollection(name).update(where, set, true, false);
  162.             
  163.         } catch (Exception e) {
  164.             e.printStackTrace();
  165.         }

  166.     }

  167.     /**
  168.      * 只更新存在的数据,不会新增. 批量更新.
  169.      * @param name
  170.      * @param setFields
  171.      * @param whereFields
  172.      */
  173.     public void updateExistDataWithBatch(String name, DBObject set, DBObject where) {

  174.         try {
  175.             
  176.             getCollection(name).update(where, new BasicDBObject("$set", set), false, true);
  177.             
  178.         } catch (Exception e) {
  179.             e.printStackTrace();
  180.         }

  181.     }

  182.     /**
  183.      * 按照ObjectId,批量更新.<br>
  184.      * 因massageToObjectId()删除,所以MongoDB驱动包版本最高为2.10.1(含)<br>
  185.      * 2.10.1以上版本无此方法,故需要自行确定ObjectId.<br>
  186.      * 待有时间找到该方法的替代方法.
  187.      * @param name
  188.      * @param ids
  189.      * @param set
  190.      */
  191.     public void updateBatchByObjectId(String name, String ids, DBObject set) {
  192.          
  193.         try {
  194.             
  195.             if (ids == null || ids == "")
  196.                 return;
  197.             
  198.             String[] id = ids.split(",");
  199.             
  200.             for (int i = 0; i < id.length; i++) {
  201.                  
  202.                 BasicDBObject dest = new BasicDBObject();
  203.                 BasicDBObject doc = new BasicDBObject();
  204.                 dest.put("_id", ObjectId.massageToObjectId(id[i]));
  205.                 doc.put("$set", set);
  206.                 getCollection(name).update(dest, doc, false, true);
  207.                  
  208.             }
  209.             
  210.         } catch (Exception e) {
  211.             e.printStackTrace();
  212.         }


  213.     }

  214.     /**
  215.      * 查询全部
  216.      * @param name
  217.      * @return
  218.      */
  219.     public List<DBObject> findAll(String name) {

  220.         try {
  221.             
  222.             return getCollection(name).find().toArray();
  223.             
  224.         } catch (Exception e) {
  225.             e.printStackTrace();
  226.         }

  227.         return null;
  228.          
  229.     }

  230.     /**
  231.      * 查询1条记录
  232.      * @param name
  233.      * @param obj
  234.      * @return
  235.      */
  236.     public DBObject findOne(String name, DBObject obj) {

  237.         try {
  238.             
  239.             DBCollection coll = getCollection(name);
  240.             return coll.findOne(obj);
  241.             
  242.         } catch (Exception e) {
  243.             e.printStackTrace();
  244.         }
  245.          
  246.         return null;

  247.     }

  248.     /**
  249.      * 查询指定条数的记录
  250.      * @param name
  251.      * @param obj
  252.      * @param limit
  253.      * @return
  254.      */
  255.     public List<DBObject> find(String name, DBObject obj, int limit) {
  256.          
  257.         try {
  258.             
  259.             DBCollection coll = getCollection(name);
  260.             DBCursor c = coll.find(obj).limit(limit);
  261.             
  262.             if (c != null){
  263.                  
  264.                 List<DBObject> list = new ArrayList<DBObject>();
  265.                 list = c.toArray();
  266.                  
  267.                 return list;
  268.                  
  269.             }
  270.             
  271.         } catch (Exception e) {
  272.             e.printStackTrace();
  273.         }
  274.          
  275.         return null;
  276.          
  277.     }

  278.     /**
  279.      * 查询符合的全部数据
  280.      * @param name
  281.      * @param where
  282.      * @return
  283.      */
  284.     public List<DBObject> find(String name, DBObject where) {
  285.          
  286.         try {
  287.             
  288.             DBCursor c = getCollection(name).find(where);
  289.             
  290.             if (c != null) {
  291.                  
  292.                 List<DBObject> list = new ArrayList<DBObject>();
  293.                 list = c.toArray();
  294.                  
  295.                 return list;
  296.                  
  297.             }
  298.             
  299.         } catch (Exception e) {
  300.             e.printStackTrace();
  301.         }

  302.         return null;

  303.     }
  304.      
  305.     /**
  306.      * 返回Queue的查询
  307.      * @param name
  308.      * @param where
  309.      * @return
  310.      * @throws Exception
  311.      */
  312.     public LinkedBlockingQueue<DBObject> findQueue(String name, DBObject where) {
  313.          
  314.         try {
  315.             
  316.             LinkedBlockingQueue<DBObject> queue = new LinkedBlockingQueue<DBObject>();
  317.             
  318.             DBCursor c = getCollection(name).find(where);
  319.             
  320.             if (c != null) {
  321.                  
  322.                 for (DBObject obj : c) {
  323.                     obj = c.next();
  324.                     queue.offer(obj);
  325.                 }
  326.                  
  327.                 return queue;
  328.                  
  329.             }
  330.             
  331.         } catch (Exception e) {
  332.             e.printStackTrace();
  333.         }

  334.         return null;

  335.     }

  336.     /**
  337.      * 关闭Mongo链接
  338.      */
  339.     public void close() {
  340.          
  341.         try {
  342.             
  343.             if (mongo != null) {
  344.                  
  345.                 mongo.close();
  346.                 log.info("MongoClient has benn closed...");
  347.                  
  348.             }
  349.             
  350.         } catch (Exception e) {
  351.             e.printStackTrace();
  352.         }

  353.     }

  354. }
复制代码
SystemMessage.java
  1. package com.liloo.util;

  2. import java.util.MissingResourceException;
  3. import java.util.ResourceBundle;

  4. /**
  5. * 获取配置文件参数
  6. * @作者    Liloo
  7. * @E-mail liloo@liloo.top
  8. * @时间    2015年7月29日
  9. * @版权    © Liloo 版权所有.
  10. */
  11. public class SystemMessage {

  12.     private SystemMessage() {
  13.          
  14.     }

  15.     /**
  16.      * 从配置文件获取参数
  17.      * @param bundle_name
  18.      * @param key
  19.      * @return
  20.      */
  21.     public static String getString(String bundle_name,String key) {
  22.          
  23.         try {
  24.             
  25.             return ResourceBundle.getBundle(bundle_name).getString(key);
  26.             
  27.         } catch (MissingResourceException e) {
  28.             return '!' + key + '!';
  29.         }
  30.          
  31.     }

  32. }
复制代码

论坛徽章:
59
2015七夕节徽章
日期:2015-08-24 11:17:25ChinaUnix专家徽章
日期:2015-07-20 09:19:30每周论坛发贴之星
日期:2015-07-20 09:19:42ChinaUnix元老
日期:2015-07-20 11:04:38荣誉版主
日期:2015-07-20 11:05:19巳蛇
日期:2015-07-20 11:05:26CU十二周年纪念徽章
日期:2015-07-20 11:05:27IT运维版块每日发帖之星
日期:2015-07-20 11:05:34操作系统版块每日发帖之星
日期:2015-07-20 11:05:36程序设计版块每日发帖之星
日期:2015-07-20 11:05:40数据库技术版块每日发帖之星
日期:2015-07-20 11:05:432015年辞旧岁徽章
日期:2015-07-20 11:05:44
2 [报告]
发表于 2015-08-12 10:50 |只看该作者
和JDBC一样,需要连接驱动。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP