欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java操作MongoDB数据库示例分享

程序员文章站 2022-05-16 23:13:29
mongodb是一个文档型数据库,是nosql家族中最重要的成员之一,以下代码封装了mongodb的基本操作。 mongodbconfig.java packa...

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();
  }
}