新建maven项目
pom.xml
4.0.0
com.gm.mongoDB
mongoDB
0.0.1-SNAPSHOT
org.apache.logging.log4j
log4j-api
2.7
org.apache.logging.log4j
log4j-core
2.7
org.slf4j
slf4j-log4j12
1.7.2
org.mongodb
mongodb-driver
3.6.3
log4j.properties
### set log levels ###
log4j.rootLogger = debug , stdout, D , E
### 输出到控制台 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
###log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{ 1 }:%L - %m%n
### 输出到日志文件 ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = logs/log.log
log4j.appender.D.Append = true
## 输出DEBUG级别以上的日志
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### 保存Debug信息到单独文件 ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
## 异常日志文件名
log4j.appender.D.File = logs/error.log
log4j.appender.D.Append = true
## 只输出ERROR级别以上的日志!!!
log4j.appender.D.Threshold = ERROR
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### 保存异常信息到单独文件 ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [%p] - %m%n
MongoHelper
package com;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
public class MongoHelper {
private static final Logger logger = LoggerFactory
.getLogger(MongoHelper.class);
static final String DBName = "mydbs";
static final String ServerAddress = "192.168.174.200";
static final int PORT = 29017;
public MongoHelper() {
}
public MongoClient getMongoClient() {
MongoClient mongoClient = null;
try {
// 连接到 mongodb 服务
mongoClient = new MongoClient(ServerAddress, PORT);
logger.debug("Connect to mongodb successfully");
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
return mongoClient;
}
public MongoDatabase getMongoDataBase(MongoClient mongoClient) {
MongoDatabase mongoDataBase = null;
try {
if (mongoClient != null) {
// 连接到数据库
mongoDataBase = mongoClient.getDatabase(DBName);
logger.debug("Connect to DataBase successfully");
} else {
throw new RuntimeException("MongoClient不能够为空");
}
} catch (Exception e) {
e.printStackTrace();
}
return mongoDataBase;
}
public MongoDatabase getMongoDataBase() {
MongoDatabase mongoDataBase = null;
try {
// 连接到数据库
mongoDataBase = getMongoDataBase(getMongoClient());
} catch (Exception e) {
e.printStackTrace();
}
return mongoDataBase;
}
public void closeMongoClient(MongoDatabase mongoDataBase,
MongoClient mongoClient) {
if (mongoDataBase != null) {
mongoDataBase = null;
}
if (mongoClient != null) {
mongoClient.close();
}
logger.debug("CloseMongoClient successfully");
}
}
MongoDao
package com;
import java.util.List;
import java.util.Map;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;
/**
* MongoDB数据操作接口
*
*/
public interface MongoDao {
/**
* 根据id检索文档
*
* @param db
* @param table
* @param id
* @return
* @throws Exception
*/
public Map queryByID(MongoDatabase db, String table,
Object id) throws Exception;
/**
* 根据doc检索文档集合,当doc是空的时候检索全部
*
* @param db
* @param table
* @param doc
* @return
* @throws Exception
*/
public List
MongoDaoImpl
package com;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
/**
* MongoDB数据操作实现类
*
*/
public class MongoDaoImpl implements MongoDao {
private static final Logger logger = LoggerFactory
.getLogger(MongoDaoImpl.class);
public Map queryByID(MongoDatabase db, String table,
Object id) throws Exception {
MongoCollection collection = db.getCollection(table);
BasicDBObject query = new BasicDBObject("_id", id);
// DBObject接口和BasicDBObject对象:表示一个具体的记录,BasicDBObject实现了DBObject,是key-value的数据结构,用起来和HashMap是基本一致的。
FindIterable iterable = collection.find(query);
Map jsonStrToMap = null;
MongoCursor cursor = iterable.iterator();
while (cursor.hasNext()) {
Document user = cursor.next();
String jsonString = user.toJson();
jsonStrToMap = JsonStrToMap.jsonStrToMap(jsonString);// 这里用到我自己写的方法,主要是包json字符串转换成map格式,为后面做准备,方法放在后面
}
logger.debug("检索ID完毕,db:{},table:{},id:{} ", db.getName(), table, id);
return jsonStrToMap;
}
public List> queryByDoc(MongoDatabase db, String table,
BasicDBObject doc) throws Exception {
MongoCollection collection = db.getCollection(table);
FindIterable iterable = collection.find(doc);
/**
* 1. 获取迭代器FindIterable 2. 获取游标MongoCursor
* 3.通过游标遍历检索出的文档集合
* */
List> list = new ArrayList>();
MongoCursor cursor = iterable.iterator();
while (cursor.hasNext()) {
Document user = cursor.next();
String jsonString = user.toJson();
Map jsonStrToMap = JsonStrToMap
.jsonStrToMap(jsonString);
list.add(jsonStrToMap);
}
logger.debug("检索doc完毕,db:{},table:{},doc:{} ", db.getName(), table,
doc.toJson());
return list;
}
public List> queryAll(MongoDatabase db, String table) throws Exception {
MongoCollection collection = db.getCollection(table);
FindIterable iterable = collection.find();
List> list = new ArrayList>();
MongoCursor cursor = iterable.iterator();
while (cursor.hasNext()) {
Document user = cursor.next();
String jsonString = user.toJson();
Map jsonStrToMap = JsonStrToMap
.jsonStrToMap(jsonString);
list.add(jsonStrToMap);
}
logger.debug("检索全部完毕,db:{},table:{}", db.getName(), table);
return list;
}
public List findIterable(FindIterable iterable) throws Exception {
List list = new ArrayList();
MongoCursor cursor = iterable.iterator();
while (cursor.hasNext()) {
Document doc = cursor.next();
list.add(doc);
}
cursor.close();
return list;
}
public boolean insert(MongoDatabase db, String table, Document doc) throws Exception {
MongoCollection collection = db.getCollection(table);
collection.insertOne(doc);
long count = collection.count(doc);
if (count >= 1) {
logger.debug("文档插入成功,影响条数:{},db:{},table:{},doc:{} ", count,
db.getName(), table, doc.toJson());
return true;
} else {
logger.debug("文档插入失败,影响条数:{},db:{},table:{},doc:{} ", count,
db.getName(), table, doc.toJson());
return false;
}
}
public boolean insertMany(MongoDatabase db, String table, List doc) throws Exception {
MongoCollection collection = db.getCollection(table);
long preCount = collection.count();
collection.insertMany(doc);
long nowCount = collection.count();
if ((nowCount - preCount) == doc.size()) {
logger.debug("文档插入成功,影响条数:{},db:{},table:{}", doc.size(),
db.getName(), table);
return true;
} else {
logger.debug("文档插入失败,影响条数:{},db:{},table:{}",
(nowCount - preCount), db.getName(), table);
return false;
}
}
public boolean delete(MongoDatabase db, String table, BasicDBObject doc) throws Exception {
MongoCollection collection = db.getCollection(table);
DeleteResult deleteManyResult = collection.deleteMany(doc);
long deletedCount = deleteManyResult.getDeletedCount();
if (deletedCount > 0) {
logger.debug("文档删除成功,影响条数:{},db:{},table:{},doc:{} ", deletedCount,
db.getName(), table, doc.toJson());
return true;
} else {
logger.debug("文档删除失败,影响条数:{},db:{},table:{},doc:{} ", 0,
db.getName(), table, doc.toJson());
return false;
}
}
public boolean deleteOne(MongoDatabase db, String table, BasicDBObject doc) throws Exception {
MongoCollection collection = db.getCollection(table);
DeleteResult deleteOneResult = collection.deleteOne(doc);
long deletedCount = deleteOneResult.getDeletedCount();
System.out.println("删除的数量: " + deletedCount);
if (deletedCount == 1) {
logger.debug("文档删除成功,影响条数:{},db:{},table:{},doc:{} ", deletedCount,
db.getName(), table, doc.toJson());
return true;
} else {
logger.debug("文档删除失败,影响条数:{},db:{},table:{},doc:{} ", 0,
db.getName(), table, doc.toJson());
return false;
}
}
public boolean update(MongoDatabase db, String table,
BasicDBObject whereDoc, BasicDBObject updateDoc) throws Exception {
MongoCollection collection = db.getCollection(table);
UpdateResult updateManyResult = collection.updateMany(whereDoc,
new Document("$set", updateDoc));
long modifiedCount = updateManyResult.getModifiedCount();
System.out.println("修改的数量: " + modifiedCount);
if (modifiedCount > 0) {
logger.debug(
"文档更新成功,影响条数:{},db:{},table:{},whereDoc:{},updateDoc:{} ",
modifiedCount, db.getName(), table, whereDoc.toJson(),
updateDoc.toJson());
return true;
} else {
logger.debug(
"文档更新成功,影响条数:{},db:{},table:{},whereDoc:{},updateDoc:{} ",
0, db.getName(), table, whereDoc.toJson(),
updateDoc.toJson());
return false;
}
}
public boolean updateOne(MongoDatabase db, String table,
BasicDBObject whereDoc, BasicDBObject updateDoc) throws Exception {
MongoCollection collection = db.getCollection(table);
UpdateResult updateOneResult = collection.updateOne(whereDoc,
new Document("$set", updateDoc));
long modifiedCount = updateOneResult.getModifiedCount();
System.out.println("修改的数量: " + modifiedCount);
if (modifiedCount == 1) {
logger.debug(
"文档更新成功,影响条数:{},db:{},table:{},whereDoc:{},updateDoc:{} ",
1, db.getName(), table, whereDoc.toJson(),
updateDoc.toJson());
return true;
} else {
logger.debug(
"文档更新成功,影响条数:{},db:{},table:{},whereDoc:{},updateDoc:{} ",
0, db.getName(), table, whereDoc.toJson(),
updateDoc.toJson());
return false;
}
}
public void createCol(MongoDatabase db, String table) throws Exception {
db.createCollection(table);
logger.debug("集合创建成功,db:{},table:{}", db.getName(), table);
}
public void dropCol(MongoDatabase db, String table) throws Exception {
db.getCollection(table).drop();
logger.debug("集合删除成功,db:{},table:{}", db.getName(), table);
}
}
JsonStrToMap
package com;
import java.util.HashMap;
import java.util.Map;
import com.mongodb.util.JSON;
public class JsonStrToMap {
/**
* json 字符串转化为map格式
*
* @param jsonString
* @return
*/
public static Map jsonStrToMap(String jsonString) {
Object parseObj = JSON.parse(jsonString); // 反序列化 把json 转化为对象
Map map = (HashMap) parseObj; // 把对象转化为map
return map;
}
}