2013-05-16 38 views
-2

每个人都在Java中创建的通用服务类,我想在Java中创建服务类(一个非常通用的),这将接受所有必需的参数从MongoDB中读取的集合。并返回JSON字符串作为结果。从MongoDB的读取采集

+0

这不是一个非常有建设性的“问题”。如果您需要帮助,请展示一些努力。 – NilsH

+1

@NilsH回去工作! ;) – vikingsteve

+0

@ Nilsh,你是对的,但我也发布了答案!这是一种方便的方式来设计一个服务,它可以通过排序和基本搜索谓词读取任何类型的集合。 –

回答

0

下面是执行此操作的快速指南。

先决条件:用于mongodb的Java驱动程序。 MongoDb的基本知识。

假设:

  1. 所有必需的参数传递从MongoDB的读取集合。

这里是需要PARAMS的快速列表。

serverNameUrl - 这是mongodb运行的服务器的路径,例如, “localhost”

dbName - 数据库的名称。说“大学”数据库。

collectionName - 集合的名称。

fieldValuePair - 在这里,我们有两个seaprators recviing的字段值以字符串形式(:,)。说我们想'名字','Empno','部门''所有员工'部门= ABC'。那么这个值将是“名称,Empno,部门:ABC”。

fVSeaprator-用于现场和值这个seaprator字符串,这里是“:”。在此字段之间用在

vFSeaprator-这seaprator字符串是“”。

sortField-Sortfield。说EMPNO

sortDirection- Sortdirection说 “-1” DESC(默认为DESC)。

这里是相同的代码!

package com.service.mongo; 

import java.util.HashMap; 
import java.util.Iterator; 
import java.util.Map; 
import java.util.Set; 

import com.mongodb.BasicDBObject; 
import com.mongodb.DB; 
import com.mongodb.DBCollection; 
import com.mongodb.DBCursor; 
import com.mongodb.MongoClient; 
import com.mongodb.util.JSON; 
import com.xp.util.Utils; 

public class TestGenericService { 

public static void main(String[] args) { 
    //Start. This return a JSON string. 
    String result =readQueryOfMongo("localhost","test","employeeCollection","Name,Empno,Dept:ABC",":",",","Empno",""); 
    System.out.println(result); 
} 


public static String readQueryOfMongo( 

     String serverNameUrl , 
     String dbName , 
     String collectionName, 
     String fieldValuePair, 
     String fVSeaprator, 
     String vFSeaprator, 
     String sortField, 
     String sortDirection 
) 
{ 
    DB db; 
    DBCollection table = null; 
    DBCursor cursor = null; 
    String result=null; 
    BasicDBObject sortPredicate = new BasicDBObject(); 
    try 
    { 

     Map<String, String> fieldValuePairMap = new HashMap<String, String>(); 

     System.out.println("ServerName:"+serverNameUrl+"\nDatabase Name:"+dbName+"\nCollection Name:"+collectionName); 

     //Configure the server, db and collection. 
     MongoClient mongoClient = new MongoClient(serverNameUrl); 

     db = mongoClient.getDB(dbName); 

     System.out.println(db.getLastError()); 

     if (db.collectionExists(collectionName)) 
     { 
      table = db.getCollection(collectionName); 

     } 
     else 
     { 
      throw new Exception("Collection doesn't exist"); 
     } 

     //Define SortPredicate. 
     if(sortField!= null) 
     { 
      if(sortDirection==null ||sortDirection.trim().length()==0) 
       sortDirection="-1";//Default sort-order should be DESC. 

      sortPredicate.put(sortField, Integer.parseInt(sortDirection)); 
     } 

     if (null != fieldValuePair && fieldValuePair.trim().length() > 0) 

     { 
      BasicDBObject searchQuery = new BasicDBObject(); 

      fieldValuePairMap = parseStringToMap(fieldValuePair, fVSeaprator, vFSeaprator); 

      System.out.println(fieldValuePairMap.size()); 

      BasicDBObject fields1 = new BasicDBObject("_id",false); 


      if(fieldValuePairMap.size()>0) 
      { 
       Set keySet = fieldValuePairMap.keySet(); 
       Iterator keyIter = keySet.iterator(); 
       String tempKey; 
       while (keyIter.hasNext()) 
       { 
        tempKey = keyIter.next().toString(); 
        fields1.append(tempKey, true); 
        if(fieldValuePairMap.get(tempKey)!=null) 
         searchQuery.put(tempKey, fieldValuePairMap.get(tempKey)); 
       } 

       cursor = table.find(searchQuery,fields1).sort(sortPredicate); 
      } 

     } 
     else 
     { 
      cursor = table.find().sort(sortPredicate); 
     } 
     result = parseStubJson(cursor, collectionName); 

    }catch (Exception e) { 
     e.printStackTrace(); 

    } 
    return result; 
} 

public static String parseStubJson(DBCursor dBCursor, String stubName) 
{ 
    System.out.println("Creating a JSON stub of:"+stubName); 

    String response="{"+"\""+stubName+"\":["; 
    int i=0; 
    int j= dBCursor.count(); 
    while (dBCursor.hasNext()) 
    { 
     i++; 
     response += JSON.parse(dBCursor.next().toString()); 
     if(j>i) 
      response +=","; 
    } 

    response += "]}"; 
    return response; 
} 

public static Map<String, String> parseStringToMap(String kerValuePair,String seprator1,String seprator2) 
{ 
    Map<String, String> myMap = new HashMap<String, String>(); 

    String[] pairs = kerValuePair.split(seprator2); 
    for (int i=0;i<pairs.length;i++) { 
     String pair = pairs[i]; 
     String[] keyValue = pair.split(seprator1); 
     if(keyValue.length > 1) 
      myMap.put(keyValue[0], keyValue[1]); 
     else 
      myMap.put(pairs[i], null); 
    } 

    Iterator itr = myMap.entrySet().iterator(); 
    while (itr.hasNext()) { 
     Object object = (Object) itr.next(); 
     System.out.println(object.toString()); 
    } 
    return myMap; 
} 

}

注:这上面的代码返回导致JSON字符串形式,可以使用在客户端的任何解析器和转换结果的要求列表或存根。 是的,你可能会觉得上面的例子是用SQL心态写的,这不是NOSQL(mongodb)的最佳使用,但是为了理解mongodb中的基本读操作,这非常有用。