版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27384505/article/details/78646800
最近后台需要写mongodb与spring项目的整合接口,参阅了网上资料后自己写出了几个方法来分享参考
一:maven引用
<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.2.2</version>
</dependency>
3.2版本以上的都可以,按照个人喜好就行
二:连接mongo配置
package com.suncar.core.util;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
public class MongoHelper {
static final String DBName = "abc";
static final String ServerAddress = "127.0.0.1";
static final int PORT = 27017;
public MongoHelper(){
}
public MongoClient getMongoClient( ){
MongoClient mongoClient = null;
try {
// 连接到 mongodb 服务
mongoClient = new MongoClient(ServerAddress, PORT);
System.out.println("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);
System.out.println("Connect to DataBase successfully");
} else {
throw new RuntimeException("MongoClient不能够为空");
}
} catch (Exception e) {
e.printStackTrace();
}
return mongoDataBase;
}
public void closeMongoClient(MongoDatabase mongoDataBase,MongoClient mongoClient ) {
if (mongoDataBase != null) {
mongoDataBase = null;
}
if (mongoClient != null) {
mongoClient.close();
}
System.out.println("CloseMongoClient successfully");
}
}
连接服务器地址与数据库都可以定义到config配置里,因项目没有需求暂时不用考虑
三:Dao层编写
package com.suncar.core.dao;
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 org.springframework.stereotype.Repository;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
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;
import com.mongodb.util.JSON;
import com.suncar.core.util.MongoHelper;
@Repository
public class MongoDbDao {
MongoHelper mongoHelper = new MongoHelper();
MongoClient mongoClient = mongoHelper.getMongoClient();
MongoDatabase mongoDataBase = mongoHelper.getMongoDataBase(mongoClient);
public static final Logger logger = LoggerFactory
.getLogger(MongoDbDao.class);
public Map<String, Integer> queryByID(String table,
Object Id) throws Exception {
MongoCollection<Document> collection = mongoDataBase.getCollection(table);
BasicDBObject query = new BasicDBObject("_id", Id);
// DBObject接口和BasicDBObject对象:表示一个具体的记录,BasicDBObject实现了DBObject,是key-value的数据结构,用起来和HashMap是基本一致的。
FindIterable<Document> iterable = collection.find(query);
Map<String, Integer> jsonStrToMap = null;
MongoCursor<Document> cursor = iterable.iterator();
while (cursor.hasNext()) {
Document user = cursor.next();
String jsonString = user.toJson();
jsonStrToMap = jsonStrToMap(jsonString);// 这里用到我自己写的方法,主要是包json字符串转换成map格式,为后面做准备,方法放在后面
}
System.out.println("检索ID完毕");
return jsonStrToMap;
}
/**
* 根据一个doc,来检索,当doc是空的时候检索全部
* @param db
* @param table
* @param doc
*/
public List<Map<String,Integer>> queryByDoc(String table, BasicDBObject doc) {
MongoCollection<Document> collection = mongoDataBase.getCollection(table);
FindIterable<Document> iterable = collection.find(doc);
/**
* 1. 获取迭代器FindIterable<Document>
* 2. 获取游标MongoCursor<Document>
* 3. 通过游标遍历检索出的文档集合
* */
List<Map<String,Integer>> list = new ArrayList<Map<String,Integer>>();
MongoCursor<Document> cursor = iterable.iterator();
while (cursor.hasNext()) {
Document user = cursor.next();
String jsonString = user.toJson();
Map<String, Integer> jsonStrToMap = jsonStrToMap(jsonString);
list.add(jsonStrToMap);
}
System.out.println("检索doc完毕");
return list;
}
/**
* 检索全部并返回迭代器
* @param db
* @param table
*/
public List<Map<String,Integer>> queryAll(String table) {
MongoCollection<Document> collection = mongoDataBase.getCollection(table);
FindIterable<Document> iterable = collection.find();
List<Map<String,Integer>> list = new ArrayList<Map<String,Integer>>();
MongoCursor<Document> cursor = iterable.iterator();
while (cursor.hasNext()) {
Document user = cursor.next();
String jsonString = user.toJson();
Map<String, Integer> jsonStrToMap = jsonStrToMap(jsonString);
list.add(jsonStrToMap);
}
System.out.println("检索全部完毕");
return list;
}
/**
* 便利迭代器FindIterable<Document>
*/
public void printFindIterable(FindIterable<Document> iterable){
MongoCursor<Document> cursor = iterable.iterator();
while (cursor.hasNext()) {
Document user = cursor.next();
System.out.println(user.toJson());
}
cursor.close();
}
public boolean insert(String table, Document document) {
MongoCollection<Document> collection = mongoDataBase.getCollection(table);
collection.insertOne(document);
long count = collection.count(document);
System.out.println("count: "+count);
if(count == 1){
System.out.println("文档插入成功");
return true;
}else{
System.out.println("文档插入成功");
return false;
}
}
/**
* insert many
*
* @param db
* @param table
* @param document
*/
public boolean insertMany(String table,
List<Document> documents) {
MongoCollection<Document> collection = mongoDataBase.getCollection(table);
long preCount = collection.count();
collection.insertMany(documents);
long nowCount = collection.count();
System.out.println("插入的数量: " + (nowCount - preCount));
if ((nowCount - preCount) == documents.size()) {
System.out.println("文档插入多个成功");
return true;
} else {
System.out.println("文档插入多个失败");
return false;
}
}
public boolean delete( String table, BasicDBObject document) {
MongoCollection<Document> collection = mongoDataBase.getCollection(table);
DeleteResult deleteManyResult = collection.deleteMany(document);
long deletedCount = deleteManyResult.getDeletedCount();
System.out.println("删除的数量: " + deletedCount);
if (deletedCount > 0) {
System.out.println("文档删除多个成功");
return true;
} else {
System.out.println("文档删除多个失败");
return false;
}
}
/**
* 删除一个
*
* @param db
* @param table
* @param document
*/
public boolean deleteOne(String table,
BasicDBObject document) {
MongoCollection<Document> collection = mongoDataBase.getCollection(table);
DeleteResult deleteOneResult = collection.deleteOne(document);
long deletedCount = deleteOneResult.getDeletedCount();
System.out.println("删除的数量: " + deletedCount);
if (deletedCount == 1) {
System.out.println("文档删除一个成功");
return true;
} else {
System.out.println("文档删除一个失败");
return false;
}
}
public boolean update( String table,
BasicDBObject whereDoc, BasicDBObject updateDoc) {
MongoCollection<Document> collection = mongoDataBase.getCollection(table);
UpdateResult updateManyResult = collection.updateMany(whereDoc,
new Document("$set", updateDoc));
long modifiedCount = updateManyResult.getModifiedCount();
System.out.println("修改的数量: " + modifiedCount);
if (modifiedCount > 0) {
System.out.println("文档更新多个成功");
return true;
} else {
System.out.println("文档更新失败");
return false;
}
}
/**
* update one Data
*
* @param db
* @param table
* @param whereDoc
* @param updateDoc
*/
public boolean updateOne( String table,
BasicDBObject whereDoc, BasicDBObject updateDoc) {
MongoCollection<Document> collection = mongoDataBase.getCollection(table);
UpdateResult updateOneResult = collection.updateOne(whereDoc,
new Document("$set", updateDoc));
long modifiedCount = updateOneResult.getModifiedCount();
System.out.println("修改的数量: " + modifiedCount);
if (modifiedCount == 1) {
System.out.println("文档更新一个成功");
return true;
} else {
System.out.println("文档更新失败");
return false;
}
}
/**
* create collection
*
* @param db
* @param table
*/
public void createCol( String table) {
mongoDataBase.createCollection(table);
System.out.println("集合创建成功");
}
/**
* drop a collection
*
* @param db
* @param table
*/
public void dropCol(String table) {
mongoDataBase.getCollection(table).drop();
System.out.println("集合删除成功");
}
public static Map<String, Integer> jsonStrToMap(String jsonString) {
Object parseObj = JSON.parse(jsonString); // 反序列化 把json 转化为对象
Map<String, Integer> map = (Map<String, Integer>) parseObj; // 把对象转化为map
return map;
}
}
这是参考其他作者的dao方法,个人修改了一些方法,可以更方便的适用于java
四:Service层
package com.suncar.core.services;
import java.util.List;
import java.util.Map;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mongodb.BasicDBObject;
import com.suncar.core.dao.MongoDbDao;
@Service
public class MongodbService {
@Autowired
private MongoDbDao mongodbdao;
/**
* 获取当前表下所有数据
* @param table
* @return
*/
public List<Map<String,Integer>> queryAll(String table){
return mongodbdao.queryAll(table);
}
/**
* 插入数据
* @param table
* @param document
* @return
*/
public boolean insert(String table, Document document){
return mongodbdao.insert(table,document);
}
/**
* 删除一个
* @param table
* @param document
* @return
*/
public boolean deleteOne(String table, BasicDBObject document){
return mongodbdao.deleteOne(table, document);
}
/**
* 删除所有
* @param table
* @param document
* @return
*/
public boolean delete(String table, BasicDBObject document){
return mongodbdao.delete(table, document);
}
/**
* 更新一个
* @param table
* @param whereDoc
* @param updateDoc
* @return
*/
public boolean updateOne(String table,
BasicDBObject whereDoc, BasicDBObject updateDoc){
return mongodbdao.updateOne(table, whereDoc, updateDoc);
}
/**
* 更新所有
* @param table
* @param whereDoc
* @param updateDoc
* @return
*/
public boolean update(String table,
BasicDBObject whereDoc, BasicDBObject updateDoc){
return mongodbdao.update(table, whereDoc, updateDoc);
}
}
基本都是调用dao的方法,不过整合了spring作为接口更方便易用