java實現mongo資料庫的CRUD操作__資料庫

來源:互聯網
上載者:User

1.  下載mongo-java-driver.jar包至項目中。


2.  

package cn.nubia.apps.mongo;public interface DBTemplate<T> {public T fetchList(String tableName);public void insert(String tableName);}

3. 

package cn.nubia.apps.mongo;import com.mongodb.MongoClientOptions;public class MongoClientOptionsBuilder {private int connectionsPerHost;private boolean autoConnectRetry;private int threadsAllowed;private int maxWaitTime;private int connectTimeout;public int getConnectionsPerHost() {return connectionsPerHost;}public void setConnectionsPerHost(int connectionsPerHost) {this.connectionsPerHost = connectionsPerHost;}public boolean isAutoConnectRetry() {return autoConnectRetry;}public void setAutoConnectRetry(boolean autoConnectRetry) {this.autoConnectRetry = autoConnectRetry;}public int getThreadsAllowed() {return threadsAllowed;}public void setThreadsAllowed(int threadsAllowed) {this.threadsAllowed = threadsAllowed;}public int getMaxWaitTime() {return maxWaitTime;}public void setMaxWaitTime(int maxWaitTime) {this.maxWaitTime = maxWaitTime;}public int getConnectTimeout() {return connectTimeout;}public void setConnectTimeout(int connectTimeout) {this.connectTimeout = connectTimeout;}public MongoClientOptions build() {MongoClientOptions.Builder build = new MongoClientOptions.Builder();//與目標資料庫能建立的最大連結數量build.connectionsPerHost(connectionsPerHost);//build.autoConnectRetry(autoConnectRetry);//當所有的connection都在使用中,則每個connection上可以有threadsAllowed個線程在排隊等待中build.threadsAllowedToBlockForConnectionMultiplier(threadsAllowed);build.maxWaitTime(maxWaitTime);build.connectTimeout(connectTimeout);return build.build();}}

4.

package cn.nubia.apps.mongo;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.MongoClient;public class MongoTemplate {private MongoClient mongoClient;private String dbName;public MongoClient getMongoClient() {return mongoClient;}public void setMongoClient(MongoClient mongoClient) {this.mongoClient = mongoClient;}public String getDbName() {return dbName;}public void setDbName(String dbName) {this.dbName = dbName;}public DB getDB() {return mongoClient.getDB(dbName);}public DB getDB(String dbname) {return mongoClient.getDB(dbname);}public DBCollection getDBCollection(String collectionName) {return getDB().getCollection(collectionName);}public DBCollection getDBCollection(String dbName,String collectionName) {return getDB(dbName).getCollection(collectionName);}}

5. 

package cn.nubia.apps.mongo;import java.util.Date;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import cn.nubia.apps.test.People;import com.mongodb.AggregationOutput;import com.mongodb.BasicDBObject;import com.mongodb.DBCollection;import com.mongodb.DBCursor;import com.mongodb.DBObject;import com.mongodb.MapReduceCommand.OutputType;import com.mongodb.MapReduceOutput;@Componentpublic class MongoDbTemplate implements DBTemplate<DBObject>{@Autowiredprivate MongoTemplate mongoTemplate;@Overridepublic DBObject fetchList(String tableName) {DBCollection db = mongoTemplate.getDBCollection("user");DBCursor cursor = db.find();while(cursor.hasNext()) {DBObject dbo = cursor.next();System.err.println(dbo.toString());}return null;}public void insert(String tableName) {DBCollection db = mongoTemplate.getDBCollection(tableName);People p = new People();p.setName("alanlin");p.setAge(28);p.setDate(new Date());db.insert(p);//db.ensureIndex("{\"name\":1}");}public <T> List<T> mr(String tableName,String map,String reduce,DBObject query) {DBCollection coll = mongoTemplate.getDBCollection(tableName);DBCollection result = null;synchronized (tableName) {MapReduceOutput mapReduceOutput = coll.mapReduce(map, reduce, tableName + "_result",OutputType.REPLACE,query); result = mapReduceOutput.getOutputCollection();}DBCursor cur = result.find();while(cur.hasNext()) {DBObject obj = cur.next();System.err.println("value=" + obj.get("value").toString());}return null;}/** * 資料格式為 * { "_id" : ObjectId("564d7e3b178eb423a2e28928"), "name" : "alanlin", "num" : 10 }       { "_id" : ObjectId("564d7e42178eb423a2e28929"), "name" : "alanlin1", "num" : 20 }       { "_id" : ObjectId("564d7e5b178eb423a2e2892a"), "name" : "alanlin2", "num" : 30 }       { "_id" : ObjectId("564d88de178eb423a2e2892b"), "name" : "alanlin2", "num" : 30 }       { "_id" : ObjectId("5653ba0b8cdc400b73808160"), "name" : "alanlin2", "num" : 40 } *  * @param tableName */public void aggregate(String tableName) {DBCollection coll = mongoTemplate.getDBCollection(tableName);DBObject match = new BasicDBObject("$match",new BasicDBObject("name","alanlin2"));DBObject sum = new BasicDBObject();sum.put("_id", "$num");sum.put("count", new BasicDBObject("$sum","1"));DBObject group = new BasicDBObject("$group",sum);AggregationOutput out = coll.aggregate(group);String str = out.getCommandResult().toString();System.err.println("str is " + str);}}

6.  其中設定檔支援單機,以及叢集的方式。

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.1.xsd"><bean id="mongoClientOptionsBuilder" class="cn.nubia.apps.mongo.MongoClientOptionsBuilder"><property name="connectionsPerHost" value="${mongodb.opts.connectionsPerHost}" /><property name="autoConnectRetry" value="${mongodb.opts.autoConnectRetry}" /><property name="threadsAllowed" value="${mongodb.opts.threadsAllowed}" /><property name="maxWaitTime" value="${mongodb.opts.maxWaitTime}" /><property name="connectTimeout" value="${mongodb.opts.connectTimeout}" /></bean><bean id="mongoClientOptions" class="com.mongodb.MongoClientOptions" factory-bean="mongoClientOptionsBuilder"factory-method="build"></bean><bean id="mongoDbTemplate" class="cn.nubia.apps.mongo.MongoDbTemplate"></bean><!-- <bean id="mongoTemplate" class="cn.nubia.apps.mongo.MongoTemplate"><property name="mongoClient"><bean class="com.mongodb.MongoClient"><constructor-arg index="0"><bean class="com.mongodb.ServerAddress"><constructor-arg index="0" value="${mongodb.host}" /><constructor-arg index="1" type="int" value="${mongodb.port}" /></bean></constructor-arg><constructor-arg index="1" ref="mongoClientOptions" /></bean></property><property name="dbName" value="${mongodb.db}" /></bean> --><!-- 複本集群環境 --><bean id="mongoTemplate" class="cn.nubia.apps.mongo.MongoTemplate"><property name="mongoClient"><bean class="com.mongodb.MongoClient"><constructor-arg>     <list> <ref bean="serverAddress"></ref> <ref bean="serverAddress"></ref> </list></constructor-arg></bean></property><property name="dbName" value="${mongodb.db}" /></bean>    <bean id="serverAddress" class="com.mongodb.ServerAddress"><constructor-arg index="0" value="10.204.76.235" /><constructor-arg index="1" type="int" value="22017" />    </bean><bean id="serverAddress1" class="com.mongodb.ServerAddress"><constructor-arg index="0" value="10.204.76.235" /><constructor-arg index="1" type="int" value="21017" />    </bean></beans>

7.  相關設定檔

mongodb.host=mongodb.port=mongodb.db=testmongodb.opts.connectionsPerHost=50mongodb.opts.autoConnectRetry=truemongodb.opts.threadsAllowed=50mongodb.opts.maxWaitTime=120000mongodb.opts.connectTimeout=60000



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.