使用spring-data-mongodb操作mongodb

时间:2022-09-11 16:23:18

mongodb.xml

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


    <context:property-placeholder location="classpath*:mongodb.properties"  />

    <!--username="${mongo.username}"-->
    <!--password="${database.password}"-->
    <mongo:db-factory id="mongoDbFactory"
                      host="${mongo.host}"
                      port="${mongo.port}"
                      dbname="${mongo.dbname}"
    />
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    </bean>
</beans>

mongodb.properties

mongo.host=127.0.0.1
mongo.port=27017
mongo.dbname=test
#mongo.username=
#database.password=

操作mongodb的测试方法

@Resource
MongoOperations mongoOperations;

@Test
public void testMongodb(){

    User user = new User();
    user.setName("testMongodb");
    user.setAge(12);
    mongoOperations.save(user, "collectionName");
    User userGetFromMdb = mongoOperations.findOne(new Query(Criteria.where("name").is("testMongodb")), User.class, "collectionName");
    System.out.println(userGetFromMdb);
}