spring整合mongo及呼叫

木叔發表於2016-11-16

spring整合mongo(maven工程下):

1、web.xml檔案中配置需要載入的配置檔案:

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:/datasource/*.xml
            classpath:/ibatis/sql-map-client-config.xml
            classpath:/context/ctx*.xml
        </param-value>
    </context-param>

 

2、datasource資料夾下新建common-config.xml檔案,配置mongo資料來源:

<?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:mongo="http://www.springframework.org/schema/data/mongo"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/data/mongo
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="order" value="2" />
        <property name="ignoreUnresolvablePlaceholders" value="true" />
        <property name="locations">
            <list>
                <value>file:${CONFIG_DIR_PATH}/village.properties</value>
                <value>file:${CONFIG_DIR_PATH}/mongo.properties</value>
                <value>file:${CONFIG_DIR_PATH}/../system-config/jdbc.village.properties</value>
            </list>
        </property>
    </bean>
    
    <!-- mongo config -->
    <!-- Default bean name is 'mongo' -->
    <mongo:mongo id="mongoData" host="${mongo.ip}" port="${mongo.port}">
        <mongo:options connections-per-host="${mongo.connections-per-host}"
            threads-allowed-to-block-for-connection-multiplier="${mongo.threads-allowed-to-block-for-connection-multiplier}"
            connect-timeout="${mongo.connect-timeout}"
            max-wait-time="${mongo.max-wait-time}"
            auto-connect-retry="${mongo.auto-connect-retry}"
            socket-timeout="${mongo.socket-timeout}"
            slave-ok="${mongo.slave-ok}"
            write-number="${mongo.write-number}"
            write-timeout="${mongo.write-timeout}"
            write-fsync="${mongo.write-fsync}" />
    </mongo:mongo>
    
    <!-- <mongo:db-factory dbname="database" mongo-ref="mongoData" /> -->
    
    <!-- 使用者資訊配置 -->
    <!-- <bean id="userCredentials" class="org.springframework.data.authentication.UserCredentials">  
        <constructor-arg name="username"  value="userName"/>  
        <constructor-arg name="password"  value="password"/>  
    </bean> -->
    
    <bean id="testMongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="mongoData" />
        <constructor-arg name="databaseName" value="xiaomu_test" />
        <!-- <constructor-arg ref="userCredentials" /> -->
    </bean>
       
</beans>

 

3、mongo.properties檔案:

#===============================================================
#mongo
#===============================================================
mongo.ip=127.0.0.1
mongo.port=27017
mongo.connections-per-host=2
mongo.max-auto-connect-retry-time=15000L
mongo.threads-allowed-to-block-for-connection-multiplier=4
mongo.connect-timeout=10000
mongo.max-wait-time=15000
mongo.auto-connect-retry=true
mongo.socket-timeout=15000
mongo.slave-ok=true
mongo.write-number=1
mongo.write-timeout=0
mongo.write-fsync=true

 

 

4、配置service和dao方法:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
     
    <bean id="mongoService" class="com.test.service.mongo.impl.MongoServiceImpl">
        <property name="mongoDao" ref="mongoDao" />
    </bean>
    
    <bean id="mongoDao" class="com.test.dao.mongo.impl.MongoDaoImpl">
        <property name="testMongoTemplate" ref="testMongoTemplate" />
    </bean>
    
</beans>

 

 

java呼叫mongo:

注:所有的collectionName都可用bean的類名代替,表示操作一bean類名命名的collection,插入時直接傳入一個bean預設會建立一個與bean同名的collection

增加:

//資料形式為:
/*
{
   "name" : "MongoDB",
   "type" : "database",
   "count" : 1,
   "info" : {
               x : 203,
               y : 102
             }
}
*/
BasicDBObject doc = new BasicDBObject("name", "MongoDB")
        .append("type", "database")
        .append("count", 1)
        .append("info", new BasicDBObject("x", 203).append("y", 102));
testMongoTemplate.insert(doc,"testColl");
//testMongoTemplate.insertAll(users);  //users是list集合,批量插入

 

刪除:

方式一:
BasicDBObject query = new BasicDBObject("name", "MongoDB");
testMongoTemplate.remove(query, collectionName);

方式二:
Criteria criteria = Criteria.where("age").gt(20);; //年齡大於20
//Criteria criteria = Criteria.where("id").is(20;//年齡等於20
Query query2 = new Query(criteria);  
testMongoTemplate.remove(query2, collectionName);

方式三(collection物件方法刪除):
DBCollection coll = testMongoTemplate.getCollection(collectionName);//通過collection名稱獲取collection物件
coll.remove(query);

 

修改:

//普通修改
Criteria criteria = Criteria.where("id").is(123);  
Query query = new Query(criteria);  
Update update = Update.update("age", 23).set("name", "xiaomu");  
testMongoTemplate.updateFirst(query, update, collectionName);
//testMongoTemplate.updateMulti(query, update, collectionName);//修改多條資料

//根據條件查詢出來後 再去修改 
Criteria criteria = Criteria.where("id").is(123);  
Query query = new Query(criteria); 
Update update = Update.update("age",12).set("name", "xiaoli");  
testMongoTemplate.findAndModify(query, update, collectionName.getClass());//查詢出來後修改
//testMongoTemplate.findAndRemove(query, update, collectionName.getClass());//查詢出來後刪除

 

查詢:

//1、查詢一條資料(通過獲取集合用集合刪除方法刪除)
Set<String> names = testMongoTemplate.getCollectionNames();//獲取collection的所有名稱
DBCollection coll = testMongoTemplate.getCollection(collectionName);//通過collection名稱獲取collection物件
BasicDBObject query = new BasicDBObject("name", "MongoDB");
DBObject oneMessage = coll.findOne(query);//查詢一條資料


//2、多條資料查詢

//查詢j不等於3,k大於10的結果
//BasicDBObject query = new BasicDBObject("j", new BasicDBObject("$ne", 3))
//                                .append("k", new BasicDBObject("$gt", 10));
        
//查詢20 < i <= 30 的結果
//BasicDBObject query = new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30));

//多結果查詢返回遊標
DBCursor cursor = coll.find(query);//不傳查詢條件表示查詢所有集合內容
try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}

//查詢集合中所有資料
List<? extends String> allResult = testMongoTemplate.findAll(collectionName.getClass());//查詢所有

//正則匹配查詢
Query query = new Query();
Criteria criteria = Criteria.where("name").regex("^" + "xiaoli");  
query.addCriteria(criteria);
testMongoTemplate.find(query, collectionName.getClass());

//分頁查詢
//分頁
Criteria criteria = Criteria.where("age").gt(20);; //年齡大於20
Query query = new Query(criteria);
query.skip(5);  //skip跳過,表示分頁的起始位置
query.limit(10);  //每頁顯示的條數
testMongoTemplate.find(query, collectionName.getClass());

 

更過方法請參考api。

 

相關文章