Loading

spring整合mongo及调用

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。

 

posted @ 2016-11-16 09:47  梦醒点灯  阅读(5911)  评论(0编辑  收藏  举报