栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 数据库 > MongoDB

Java操作MongoDB数据库示例分享

MongoDB 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java操作MongoDB数据库示例分享

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;

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";
  
  private static Map cfgMap = new HashMap();
  private static Hashtable mongoDBs = new Hashtable();
  
  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);
    }
  }
  
  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();
    }
  }
  
  public static Mongo getMongo() {
    return mongo;
  }
  
  public static DB getDB() {
    return db;
  }
  public static List getDBNames() {
    return mongo.getDatabaseNames();
  }
  
  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


package com.posoftframework.mongodb;
import java.util.List;
import java.util.Map;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

public interface MongoService {
  public abstract DBCollection getCollection();
  
  public abstract DBObject insert(DBObject obj);
  
  public abstract void insertBatch(List list);
  
  public abstract void delete(DBObject obj);
  
  public abstract void deleteBatch(List list);
  
  public abstract long getCollectionCount();
  public abstract long getCount(DBObject query);
  public abstract List find(DBObject query);
  public abstract List find(DBObject query,DBObject sort);
  public abstract List find(DBObject query,DBObject sort,int start,int limit);
  
  public abstract void update(DBObject setFields,
      DBObject whereFields);
  public abstract List findAll();
  
  public abstract DBObject getById(String id);
  
  public List 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


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;

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 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 list) {
    if (list == null || list.isEmpty()) {
      return;
    }
    List listDB = new ArrayList();
    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 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 find(DBObject obj) {
    DBCursor cur = getCollection().find(obj);
    return DBCursor2list(cur);
  }
  @Override
  public List 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 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 DBCursor2list(DBCursor cur) {
    List list = new ArrayList();
    if (cur != null) {
      list = cur.toArray();
    }
    return list;
  }
  public void update(DBObject setFields, DBObject whereFields) {
    getCollection().updateMulti(setFields, whereFields);
  }
  public List findAll() {
    DBCursor cur = getCollection().find();
    List list = new ArrayList();
    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 getAllDBNames() {
    return MongoDBConfig.getDBNames();
  }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/173184.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号