MongoDB是一個(gè)文檔型數(shù)據(jù)庫(kù),是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數(shù)據(jù)庫(kù)參數(shù)
*/
private static MapString, String> cfgMap = new HashMapString, String>();
private static HashtableString, DB> mongoDBs = new HashtableString, DB>();
/**
* 初始化Mongo的數(shù)據(jù)庫(kù)
*/
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數(shù)據(jù)庫(kù)
*/
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的實(shí)例
*
* @return
*/
public static Mongo getMongo() {
return mongo;
}
/**
* 得到Mongo的圖片數(shù)據(jù)庫(kù)
*
* @return
*/
public static DB getDB() {
return db;
}
public static ListString> getDBNames() {
return mongo.getDatabaseNames();
}
/**
* 根據(jù)數(shù)據(jù)庫(kù)名稱,得到數(shù)據(jù)庫(kù)br/>
* 如果不存在,則創(chuàng)建一個(gè)該名稱的數(shù)據(jù)庫(kù),并設(shè)置用戶名和密碼為配置文件中的參數(shù)值/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
/************************* 版權(quán)聲明 *********************************
* *
* 版權(quán)所有:百洋軟件 *
* Copyright (c) 2010 by www.po-soft.com *
* *
************************* 變更記錄 *********************************
*
* 創(chuàng)建者:yongtree 創(chuàng)建日期: 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();
/**
* 根據(jù)數(shù)據(jù)集合的Map,插入數(shù)據(jù) map的key對(duì)應(yīng)數(shù)據(jù)庫(kù)中的DBCollection的key值
*
* @param obj
*/
public abstract DBObject insert(DBObject obj);
/**
* 根據(jù)ListMapString,Object>>結(jié)構(gòu)的數(shù)據(jù)集合,插入數(shù)據(jù)
*
* @param list
*/
public abstract void insertBatch(ListDBObject> list);
/**
* 按照條件參數(shù)集合map,刪除數(shù)據(jù)
*
* @param map
*/
public abstract void delete(DBObject obj);
/**
* 按照多種條件的并集,批量刪除數(shù)據(jù)
*
* @param list
*/
public abstract void deleteBatch(ListDBObject> list);
/**
* 得到Collection()總的記錄數(shù)
*
* @return
*/
public abstract long getCollectionCount();
public abstract long getCount(DBObject query);
public abstract ListDBObject> find(DBObject query);
public abstract ListDBObject> find(DBObject query,DBObject sort);
public abstract ListDBObject> find(DBObject query,DBObject sort,int start,int limit);
/**
* 根據(jù)whereFields參數(shù),更新setFields值
*
* @param setFields
* @param whereFields
*/
public abstract void update(DBObject setFields,
DBObject whereFields);
public abstract ListDBObject> findAll();
/**
* 根據(jù)ID找到唯一數(shù)據(jù) 有1個(gè)id字段標(biāo)記
*
* @param id
* @return
*/
public abstract DBObject getById(String id);
/**
* 獲取所有數(shù)據(jù)庫(kù)名稱
*
* @return
*/
public ListString> 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
/************************* 版權(quán)聲明 *********************************
* *
* 版權(quán)所有:百洋軟件 *
* Copyright (c) 2010 by www.po-soft.com *
* *
************************* 變更記錄 *********************************
*
* 創(chuàng)建者:yongtree 創(chuàng)建日期: 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(MapString, 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(ListDBObject> list) {
if (list == null || list.isEmpty()) {
return;
}
ListDBObject> listDB = new ArrayListDBObject>();
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(ListDBObject> 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 ListDBObject> find(DBObject obj) {
DBCursor cur = getCollection().find(obj);
return DBCursor2list(cur);
}
@Override
public ListDBObject> 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 ListDBObject> 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 ListDBObject> DBCursor2list(DBCursor cur) {
ListDBObject> list = new ArrayListDBObject>();
if (cur != null) {
list = cur.toArray();
}
return list;
}
public void update(DBObject setFields, DBObject whereFields) {
getCollection().updateMulti(setFields, whereFields);
}
public ListDBObject> findAll() {
DBCursor cur = getCollection().find();
ListDBObject> list = new ArrayListDBObject>();
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 ListString> getAllDBNames() {
return MongoDBConfig.getDBNames();
}
}
您可能感興趣的文章:- Java的idea連接mongodb數(shù)據(jù)庫(kù)的詳細(xì)教程
- Java操作MongoDB數(shù)據(jù)庫(kù)方法詳解
- Java單例模式下的MongoDB數(shù)據(jù)庫(kù)操作工具類
- Java操作Mongodb數(shù)據(jù)庫(kù)實(shí)現(xiàn)數(shù)據(jù)的增刪查改功能示例
- 【MongoDB for Java】Java操作MongoDB數(shù)據(jù)庫(kù)
- java實(shí)現(xiàn)mongodb的數(shù)據(jù)庫(kù)連接池
- Java操作MongoDB數(shù)據(jù)庫(kù)的示例代碼