您的位置:首页 > 编程语言 > Java开发

java 对 mongo 接口实现 3.0版本以上

2017-07-28 15:39 274 查看
package com.iscas.datasong.service.component.mongodb.repository;

import com.iscas.datasong.common.util.DataSongMapUtils;
import com.iscas.datasong.lib.common.DataItem;
import com.iscas.datasong.lib.common.DataSongConstant;
import com.iscas.datasong.lib.common.DataSongException;
import com.iscas.datasong.lib.common.SortOrder;
import com.iscas.datasong.lib.request.SearchDataRequest;
import com.iscas.datasong.lib.response.data.SearchDataResponse;
import com.iscas.datasong.lib.util.DataSongJsonUtils;
import com.iscas.datasong.service.component.mongodb.config.MongoConfig;
import com.iscas.datasong.service.component.mongodb.util.BJsonArray;
import com.iscas.datasong.service.component.mongodb.util.ISBean;
import com.iscas.datasong.service.component.mongodb.util.MongoClientUtil;
import com.iscas.datasong.service.component.mongodb.util.MongoQueryAnalyzer;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import org.bson.BSONObject;
import org.bson.Document;

import java.util.*;

/**
* Created by zhangqilin on 2017/7/3.
*/
public class MongoDBDataService{

private MongoConfig config;

public MongoDBDataService(MongoConfig config){
this.config = config;
}

public boolean save(String dbName, String tableName, String id, Map<String, Object> data) throws DataSongException{

//获取连接
MongoCollection<Document> collection = new MongoClientUtil(config).client(dbName,tableName);
Document document = new Document();
for (Map.Entry<String, Object> entry : data.entrySet()) {
Object obj = mapToDoc(entry.getValue());
if(entry.getValue() instanceof Map || ISBean.ISBeanOrOther(entry.getValue())){
document.put(entry.getKey(),(Document)obj);
}else if(entry.getValue() instanceof  List || entry.getValue().getClass().isArray()){
document.put(entry.getKey(),(List)obj);
}else {
document.put(entry.getKey(),obj);
}
}
//进入此处的map中已经都不包含_id
document.put(DataSongConstant.PrimaryKey, id);
boolean flag = exists(dbName,tableName,id);
if(flag){
delete(dbName,tableName,id);
}
collection.insertOne(document);
close();
return true;
}

public boolean save(String dbName, String tableName, Map<String, Map<String, Object>> datas) throws DataSongException{
//获取连接
MongoCollection<Document> collection = new MongoClientUtil(config).client(dbName,tableName);
List<Document> list = new ArrayList<Document>();
for(String id : datas.keySet()) {
Map<String, Object> data = datas.get(id);
Document document = new Document();
for (Map.Entry<String, Object> entry : data.entrySet()) {
Object obj = mapToDoc(entry.getValue());
if(entry.getValue() instanceof Map || ISBean.ISBeanOrOther(entry.getValue())){
document.put(entry.getKey(),(Document)obj);
}else if(entry.getValue() instanceof  List || entry.getValue().getClass().isArray()){
document.put(entry.getKey(),(List)obj);
}else {
document.put(entry.getKey(),obj);
}
}

//进入此处的map中已经都不包含_id
document.put(DataSongConstant.PrimaryKey, id);
boolean flag = exists(dbName,tableName,id);
if(flag){
delete(dbName,tableName,id);
}
list.add(document);
}
collection.insertMany(list);
close();
return true;
}

public Map<String,Object> findOne(String dbName, String tableName, String id) throws DataSongException{
//获取连接
MongoCollection<Document> collection = new MongoClientUtil(config).client(dbName,tableName);
Map<String,Object> map = new HashMap<>();
MongoCursor<Document> cursor = collection.find(
Filters.and(Filters.eq(DataSongConstant.PrimaryKey,id))).iterator();
while(cursor.hasNext()){
Document doc = cursor.next();
for (Map.Entry<String, Object> entry : doc.entrySet()) {
//                doc.put(entry.getKey(),entry.getValue());
map.put(entry.getKey(),entry.getValue());
}
}
close();
return map;
}

public boolean exists(String dbName, String tableName, String id) throws DataSongException{
Map<String,Object> map = findOne(dbName,tableName,id);
if(map.isEmpty()){
return false;
}
close();
return true;
}

public List<Map<String,Object>> findAll(String dbName, String tableName) throws DataSongException{
List<Map<String,Object>> list = new ArrayList<>();
//获取连接
MongoCollection<Document> collection = new MongoClientUtil(config).client(dbName,tableName);
MongoCursor<Document> cursor = collection.find().iterator();
while (cursor.hasNext()) {
Map<String,Object> map =  new HashMap<>();
Document doc = cursor.next();
for (Map.Entry<String, Object> entry : doc.entrySet()) {
map.put(entry.getKey(),entry.getValue());
}
list.add(map);
}
close();
return list;
}

public List<Map<String,Object>> findAll(String dbName, String tableName, List<String> ids) throws DataSongException{
List<Map<String,Object>> list = new ArrayList<>();
Iterator<String> it = ids.iterator();
while (it.hasNext()) {
String id = it.next();
Map<String,Object> map = findOne(dbName,tableName,id);
list.add(map);
}
close();
return list;
}

public long count(String dbName, String tableName) throws DataSongException{
//获取连接
MongoCollection<Document> collection = new MongoClientUtil(config).client(dbName,tableName);
return collection.count();
}

public boolean delete(String dbName, String tableName, String id) throws DataSongException{
//获取连接
MongoCollection<Document> collection = new MongoClientUtil(config).client(dbName,tableName);
collection.deleteMany(Filters.lte("_id", id));
close();
return true;
}

public boolean delete(String dbName, String tableName, List<String> ids) throws DataSongException{
Iterator<String> it = ids.iterator();
while (it.hasNext()) {
String id = it.next();
delete(dbName,tableName,id);
}
close();
return true;
}

public boolean deleteAll(String dbName, String tableName) throws DataSongException{
//获取连接
MongoCollection<Document> collection = new MongoClientUtil(config).client(dbName,tableName);
collection.drop();
close();
return true;
}

public boolean close()throws DataSongException{
MongoClient mongoClient = new MongoClient(config.getMONGO_DB_ADDRESS(), config.getMONGO_DB_PORT());
mongoClient.close();
return true;
}

public SearchDataResponse search(String dbName, String tableName, SearchDataRequest request) throws DataSongException{
SearchDataResponse searchDataResponse = new SearchDataResponse();

//链接数据库
//获取连接
MongoCollection<Document> collection = new MongoClientUtil(config).client(dbName,tableName);

MongoCursor<Document> cursor;
//解析查询条件
//获取查询条件主体
//查询字段及排序方式
BasicDBObject sort = new BasicDBObject();
//排序    //1是正序  -1是倒序
String orderBy = null;
LinkedHashMap<String, SortOrder> sortMap = request.getSort();
if (!(sortMap == null || sortMap.isEmpty())) {
for (String field : sortMap.keySet()) {
if (orderBy == null) {
if (sortMap.get(field) == SortOrder.ASC)
sort.put(field,1);
else
sort.put(field,-1);
} else {
if (sortMap.get(field) == SortOrder.ASC)
sort.put(field,1);
else
sort.put(field,-1);
}
}
}
int count = 0;
if(request.getSearch()==null){
cursor = collection.find().skip(request.getStart()).sort(sort).limit(request.getSize()).iterator();
count = (int)collection.count();
}else {
MongoQueryAnalyzer mongoQueryAnalyzer = new MongoQueryAnalyzer();
BasicDBObject searchCond = mongoQueryAnalyzer.mongoQueryAnalyzer(request);
//            BasicDBObject searchCond = new MongoQueryAnalyzer().mongoQueryAnalyzer(request);

cursor = collection.find(searchCond).skip(request.getStart()).sort(sort).limit(request.getSize()).iterator();
MongoCursor<Document> cursor2 =collection.find(searchCond).iterator();
while (cursor2.hasNext()){
Document doc = cursor2.next();
for (Map.Entry<String, Object> entry : doc.entrySet()) {
}
count++;
}
}
Set<String> columns = request.getColumns();
List<DataItem> resultList = new ArrayList<>();
if(columns!=null && columns.size()!=0){
while(cursor.hasNext()){
Document doc = cursor.next();
DataItem dataItem = new DataItem();
dataItem.setDBName(dbName);
dataItem.setTableName(tableName);
Iterator<String> it = columns.iterator();
Map<String,Object> data = new HashMap();
for (Map.Entry<String, Object> entry : doc.entrySet()) {
if(request.getColumns().contains(entry.getKey())){
data.put(entry.getKey(),entry.getValue());
}
if(entry.getKey().equals(DataSongConstant.PrimaryKey)){
data.put(DataSongConstant.PrimaryKey,entry.getValue());
}
}
dataItem.setSource(DataSongJsonUtils.toJson(data));
resultList.add(dataItem);
searchDataResponse.setItems(resultList);
}

searchDataResponse.setTotal(count);

}else {
while(cursor.hasNext()){
Document doc = cursor.next();
DataItem dataItem = new DataItem();
dataItem.setDBName(dbName);
dataItem.setTableName(tableName);
Map<String,Object> data = new HashMap();
for (Map.Entry<String, Object> entry : doc.entrySet()) {
data.put(entry.getKey(),entry.getValue());
}
dataItem.setSource(DataSongJsonUtils.toJson(data));
resultList.add(dataItem);
searchDataResponse.setItems(resultList);
}
searchDataResponse.setTotal(count);
}
close();
return searchDataResponse;
}

public Object mapToDoc(Object obj){
Boolean flag = new ISBean().ISBeanOrOther(obj);
if(flag){
//如果是一个bean结构。那么将这个bean转为map
Map<String, Object> map = new HashMap<>();
map= DataSongMapUtils.toMap(obj);
//处理map 调用本身
Document documentOne = new Document();
for (Map.Entry<String, Object> mapValue : map.entrySet()) {
Object tmp = mapToDoc(mapValue.getValue());
documentOne.put(mapValue.getKey(), tmp);
}
return documentOne;
} else if(obj instanceof Map){
//遍历map-》doc
Document documentOne = new Document();
Map<String,Object> map = (Map<String,Object>) obj;
for (Map.Entry<String, Object> mapValue : map.entrySet()) {
Object tmp = mapToDoc(mapValue.getValue());
documentOne.put(mapValue.getKey(), tmp);
}
return documentOne;
}else if(obj.getClass().isArray()){
List list =new BJsonArray().makearrayobject(obj);
//遍历list 调用自己
List result = new ArrayList();
for (int i =0;i<list.size();i++){
Object tmp = mapToDoc(list.
9adb
get(i));
result.add(tmp);
}
return result;
}else if(obj instanceof List){
//遍历list 调用自己
List list = new ArrayList();
List listObj = (List) obj;
for (int i =0;i<listObj.size();i++){
Object tmp = mapToDoc(listObj.get(i));
list.add(tmp);
}
return list;
}else {
return obj;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: