• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Java操作MongoDB数据库示例分享

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

MongoDB是一个文档型数据库,是NOSQL家族中最重要的成员之一,以下代码封装了MongoDB的基本操作。

MongoDBConfig.java

package com.posoftframework.mongodb;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import com.mongodb.DB;
import com.mongodb.Mongo;
/**
 * MongoDB配置类
 * 
 * @author yongtree
 * @date 2010-7-7 下午07:45:08
 * @version 1.0
 */
public class MongoDBConfig {
  private static Mongo mongo;
  private static DB db;
  private static final String MONGO_DB_ADDRESS = "localhost";
  private static final int MONGO_DB_PORT = 27017;
  private static final String MONGO_DB_USERNAME = "root";
  private static final String MONGO_DB_PASSWORD = "root";
  private static final String MONGO_DB_DBNAME = "mongodb";
  private static final String MONGO_DB_RESOURCE_FILE = "mongodb.cfg.properties";
  /**
   * Mongo数据库参数
   */
  private static Map<String, String> cfgMap = new HashMap<String, String>();
  private static Hashtable<String, DB> mongoDBs = new Hashtable<String, DB>();
  /**
   * 初始化Mongo的数据库
   */
  static {
    init();
  }
  public static File getConfigFile() {
    String path = MongoDBConfig.class.getResource("/").getPath();
    String fileName = path + MONGO_DB_RESOURCE_FILE;
    File file = new File(fileName);
    if (file.exists()) {
      return file;
    }
    return null;
  }
  @SuppressWarnings("unchecked")
  private static void initCfgMap() {
    File file = getConfigFile();
    if (file != null) {
      Properties p = new Properties();
      try {
        p.load(new FileInputStream(file));
        for (Enumeration enu = p.propertyNames(); enu.hasMoreElements();) {
          String key = (String) enu.nextElement();
          String value = (String) p.getProperty(key);
          cfgMap.put(key, value);
        }
      } catch (IOException e) {
        System.out.println("记载Mongo配置文件失败!");
        e.printStackTrace();
      }
    } else {
      cfgMap.put("mongo.db.address", MONGO_DB_ADDRESS);
      cfgMap.put("mongo.db.port", String.valueOf(MONGO_DB_PORT));
      cfgMap.put("mongo.db.username", MONGO_DB_USERNAME);
      cfgMap.put("mongo.db.password", MONGO_DB_PASSWORD);
      cfgMap.put("mongo.db.dbname", MONGO_DB_DBNAME);
    }
  }
  /**
   * 初始化Mongo数据库
   */
  private static void init() {
    initCfgMap();
    try {
      String address = cfgMap.get("mongo.db.address");
      int port = Integer.parseInt(cfgMap.get("mongo.db.port").toString());
      String dbName = cfgMap.get("mongo.db.dbname");
      String username = cfgMap.get("mongo.db.username");
      String password = cfgMap.get("mongo.db.password");
      mongo = new Mongo(address, port);
      if (dbName != null && !"".equals(dbName)) {
        db = mongo.getDB(dbName);
        if (username != null && !"".equals(username)) {
          db.addUser(username, password.toCharArray());
        }
        mongoDBs.put(dbName, db);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /**
   * 得到Mongo的实例
   * 
   * @return
   */
  public static Mongo getMongo() {
    return mongo;
  }
  /**
   * 得到Mongo的图片数据库
   * 
   * @return
   */
  public static DB getDB() {
    return db;
  }
  public static List<String> getDBNames() {
    return mongo.getDatabaseNames();
  }
  /**
   * 根据数据库名称,得到数据库<br/>
   * 如果不存在,则创建一个该名称的数据库,并设置用户名和密码为配置文件中的参数值</br>
   * 
   * @param dbName
   * @return
   */
  public static DB getDBByName(String dbName) {
    DB db = mongo.getDB(dbName);
    if (!mongoDBs.contains(db)) {
      db.addUser(cfgMap.get("mongo.db.username"), cfgMap.get(
          "mongo.db.password").toCharArray());
      mongoDBs.put(dbName, db);
    }
    return db;
  }
}

MongoService.java

/************************* 版权声明 *********************************
 *                                                               *
 *           版权所有:百洋软件                                                    *
 *     Copyright (c) 2010 by www.po-soft.com                        *
 *                                                               *
 ************************* 变更记录 *********************************
 *
 * 创建者:yongtree  创建日期: 2010-7-7
 * 备注:
 * 
 * 修改者:    修改日期:
 * 备注:
 * 
 */
package com.posoftframework.mongodb;
import java.util.List;
import java.util.Map;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
/**
 * 操作MongoDB的DAO接口
 * 
 * @author yongtree
 * @date 2010-7-7 下午04:44:43
 * @version 1.0
 */
public interface MongoService {
  public abstract DBCollection getCollection();
  /**
   * 根据数据集合的Map,插入数据 map的key对应数据库中的DBCollection的key值
   * 
   * @param obj
   */
  public abstract DBObject insert(DBObject obj);
  /**
   * 根据List<Map<String,Object>>结构的数据集合,插入数据
   * 
   * @param list
   */
  public abstract void insertBatch(List<DBObject> list);
  /**
   * 按照条件参数集合map,删除数据
   * 
   * @param map
   */
  public abstract void delete(DBObject obj);
  /**
   * 按照多种条件的并集,批量删除数据
   * 
   * @param list
   */
  public abstract void deleteBatch(List<DBObject> list);
  /**
   * 得到Collection()总的记录数
   * 
   * @return
   */
  public abstract long getCollectionCount();
  public abstract long getCount(DBObject query);
  public abstract List<DBObject> find(DBObject query);
  public abstract List<DBObject> find(DBObject query,DBObject sort);
  public abstract List<DBObject> find(DBObject query,DBObject sort,int start,int limit);
  /**
   * 根据whereFields参数,更新setFields值
   * 
   * @param setFields
   * @param whereFields
   */
  public abstract void update(DBObject setFields,
      DBObject whereFields);
  public abstract List<DBObject> findAll();
  /**
   * 根据ID找到唯一数据 有1个id字段标记
   * 
   * @param id
   * @return
   */
  public abstract DBObject getById(String id);
  /**
   * 获取所有数据库名称
   * 
   * @return
   */
  public List<String> getAllDBNames();
  public abstract String getDbName();
  public abstract void setDbName(String dbName);
  public abstract DB getDb();
  public abstract String getCollName();
  public abstract void setCollName(String collName);
}

MongoServiceImpl.java

/************************* 版权声明 *********************************
 *                                                               *
 *           版权所有:百洋软件                                                    *
 *     Copyright (c) 2010 by www.po-soft.com                        *
 *                                                               *
 ************************* 变更记录 *********************************
 *
 * 创建者:yongtree  创建日期: 2010-7-7
 * 备注:
 * 
 * 修改者:    修改日期:
 * 备注:
 * 
 */
package com.posoftframework.mongodb;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.bson.types.ObjectId;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
/**
 * 
 * @author yongtree
 * @date 2010-7-7 下午07:22:15
 * @version 1.0
 */
public class MongoServiceImpl implements MongoService {
  private String dbName;
  private String collName;
  private DB db;
  public MongoServiceImpl(String dbName, String collName) {
    this.dbName = dbName;
    this.collName = collName;
    try {
      db = MongoDBConfig.getDBByName(this.dbName);
    } catch (Throwable e) {
      e.printStackTrace();
    }
  }
  public MongoServiceImpl() {
    getDb();
  }
  public DBCollection getCollection() {
    return db.getCollection(this.collName);
  }
  public DBObject map2Obj(Map<String, Object> map) {
    DBObject obj = new BasicDBObject();
    if (map.containsKey("class") && map.get("class") instanceof Class)
      map.remove("class");
    obj.putAll(map);
    return obj;
  }
  public DBObject insert(DBObject obj) {
    getCollection().insert(obj);
    return obj;
  }
  public void insertBatch(List<DBObject> list) {
    if (list == null || list.isEmpty()) {
      return;
    }
    List<DBObject> listDB = new ArrayList<DBObject>();
    for (int i = 0; i < list.size(); i++) {
      listDB.add(list.get(i));
    }
    getCollection().insert(listDB);
  }
  public void delete(DBObject obj) {
    getCollection().remove(obj);
  }
  public void deleteBatch(List<DBObject> list) {
    if (list == null || list.isEmpty()) {
      return;
    }
    for (int i = 0; i < list.size(); i++) {
      getCollection().remove(list.get(i));
    }
  }
  public long getCollectionCount() {
    return getCollection().getCount();
  }
  public long getCount(DBObject obj) {
    if (obj != null)
      return getCollection().getCount(obj);
    return getCollectionCount();
  }
  public List<DBObject> find(DBObject obj) {
    DBCursor cur = getCollection().find(obj);
    return DBCursor2list(cur);
  }
  @Override
  public List<DBObject> find(DBObject query, DBObject sort) {
    DBCursor cur;
    if (query != null) {
      cur = getCollection().find(query);
    } else {
      cur = getCollection().find();
    }
    if (sort != null) {
      cur.sort(sort);
    }
    return DBCursor2list(cur);
  }
  @Override
  public List<DBObject> find(DBObject query, DBObject sort, int start,
      int limit) {
    DBCursor cur;
    if (query != null) {
      cur = getCollection().find(query);
    } else {
      cur = getCollection().find();
    }
    if (sort != null) {
      cur.sort(sort);
    }
    if (start == 0) {
      cur.batchSize(limit);
    } else {
      cur.skip(start).limit(limit);
    }
    return DBCursor2list(cur);
  }
  private List<DBObject> DBCursor2list(DBCursor cur) {
    List<DBObject> list = new ArrayList<DBObject>();
    if (cur != null) {
      list = cur.toArray();
    }
    return list;
  }
  public void update(DBObject setFields, DBObject whereFields) {
    getCollection().updateMulti(setFields, whereFields);
  }
  public List<DBObject> findAll() {
    DBCursor cur = getCollection().find();
    List<DBObject> list = new ArrayList<DBObject>();
    if (cur != null) {
      list = cur.toArray();
    }
    return list;
  }
  public DBObject getById(String id) {
    DBObject obj = new BasicDBObject();
    obj.put("_id", new ObjectId(id));
    DBObject result = getCollection().findOne(obj);
    return result;
  }
  public String getDbName() {
    return dbName;
  }
  public void setDbName(String dbName) {
    this.dbName = dbName;
    this.db = MongoDBConfig.getDBByName(this.dbName);
  }
  public String getCollName() {
    return collName;
  }
  public void setCollName(String collName) {
    this.collName = collName;
  }
  public DB getDb() {
    if (this.db == null) {
      if (this.dbName == null) {
        this.db = MongoDBConfig.getDB();
      } else {
        this.db = MongoDBConfig.getDBByName(this.dbName);
      }
    }
    return this.db;
  }
  public List<String> getAllDBNames() {
    return MongoDBConfig.getDBNames();
  }
}


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
查找oracle数据库表中是否存在系统关键字的方法发布时间:2022-02-08
下一篇:
关于MySQL主从复制的几种复制方式总结发布时间:2022-02-08
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap