mongodb--与spring整合

一、spring-data-mongodb

  Spring Data是Spring专门用来数据处理的一个子项目,Spring Data除了spring-data-mongodb之外还包括spring-data-jp、spring-data-redis等项目。spring-data-mongodb就是针对mongodb的一个项目。通过它我们可以对nongodb进行操作。spring-data-mongodb的项目地址为:http://projects.spring.io/spring-data-mongodb/ 。

二、实例

  例子使用maven构建并使用spring-test运行。

  pom.xml 内容如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>



    <groupId>com.yichun.test</groupId>

    <artifactId>test_yichun</artifactId>

    <version>0.0.1-SNAPSHOT</version>

    <packaging>jar</packaging>



    <name>test_yichun</name>

    <url>http://maven.apache.org</url>



    <properties>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <junit.version>4.11</junit.version>

        <spring.version>4.1.1.RELEASE</spring.version>

    </properties>



    <dependencies>

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-core</artifactId>

            <version>${spring.version}</version>

        </dependency>

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-context</artifactId>

            <version>${spring.version}</version>

        </dependency>

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-context-support</artifactId>

            <version>${spring.version}</version>

        </dependency>



        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-test</artifactId>

            <version>${spring.version}</version>

        </dependency>



        <dependency>

            <groupId>org.mongodb</groupId>

            <artifactId>mongo-java-driver</artifactId>

            <version>2.12.4</version>

        </dependency>



        <dependency>

            <groupId>org.springframework.data</groupId>

            <artifactId>spring-data-mongodb</artifactId>

            <version>1.6.1.RELEASE</version>

        </dependency>



        <dependency>

            <groupId>junit</groupId>

            <artifactId>junit</artifactId>

            <version>${junit.version}</version>

            <scope>test</scope>

        </dependency>



    </dependencies>

</project>

  spring-config-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:context="http://www.springframework.org/schema/context"

    xmlns:mongo="http://www.springframework.org/schema/data/mongo"

    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">



    <mongo:mongo host="127.0.0.1" port="27017" />

    <mongo:db-factory dbname="mongotest" mongo-ref="mongo" />



    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">

        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />

    </bean>

</beans>

  Person.java 对应于保存的文档  

package com.yichun.test.test_yichun;



public class Person {



    private String id;

    private String name;

    private int age;



    public Person() {

    }



    public Person(String name, int age) {

        this.name = name;

        this.age = age;

    }



    public Person(String id, String name, int age) {

        this.id = id;

        this.name = name;

        this.age = age;

    }



    public String getId() {

        return id;

    }



    public String getName() {

        return name;

    }



    public int getAge() {

        return age;

    }



    @Override

    public String toString() {

        return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";

    }



}

  MongoTest 主运行类

  1 package com.yichun.test.test_yichun;

  2 

  3 import java.util.ArrayList;

  4 import java.util.List;

  5 

  6 import javax.annotation.Resource;

  7 

  8 import org.junit.Test;

  9 import org.junit.runner.RunWith;

 10 import org.springframework.data.domain.Sort;

 11 import org.springframework.data.domain.Sort.Direction;

 12 import org.springframework.data.mongodb.core.FindAndModifyOptions;

 13 import org.springframework.data.mongodb.core.MongoTemplate;

 14 import org.springframework.data.mongodb.core.query.Criteria;

 15 import org.springframework.data.mongodb.core.query.Query;

 16 import org.springframework.data.mongodb.core.query.Update;

 17 import org.springframework.test.context.ContextConfiguration;

 18 import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;

 19 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

 20 

 21 import com.mongodb.WriteResult;

 22 

 23 @RunWith(SpringJUnit4ClassRunner.class)

 24 @ContextConfiguration(locations = "classpath:spring-config-mongodb.xml")

 25 public class MongoTest extends AbstractJUnit4SpringContextTests {

 26 

 27     @Resource

 28     private MongoTemplate mongoTemplate;

 29 

 30     @Test

 31     public void testAddDoc() {

 32         Person p = new Person("Joe", 34);

 33         Person p2 = new Person("1001", "Joe", 34);

 34         Person p11 = new Person("1011", "zhangsan", 20);

 35         Person p12 = new Person("1012", "zhangsan2", 21);

 36         Person p13 = new Person("1013", "zhangsan3", 23);

 37         List<Person> list = new ArrayList<Person>();

 38         list.add(p11);

 39         list.add(p12);

 40         list.add(p13);

 41         this.mongoTemplate.insert(p);// 默认保存在person集合中(与类名称一致)

 42         this.mongoTemplate.insert(p2, "person2");// 指定保存在person2集合中

 43         this.mongoTemplate.insertAll(list);// 默认保存在person集合中(与类名称一致)

 44         // mongoTemplate.insert(list, collectionName);//指定保存的集合

 45         // mongoTemplate.insert(list, Person.class);// 默认保存在person集合中(与类名称一致)

 46     }

 47 

 48     @Test

 49     public  void testFindDoc() {

 50         // 根据id查询,此id为mongo生成的id

 51         Person person = this.mongoTemplate.findById("1011", Person.class);

 52         System.out.println(person);

 53 

 54         // 使用query对象查询

 55         Query query = new Query(Criteria.where("age").is(34));

 56         person = this.mongoTemplate.findOne(query, Person.class);

 57         System.out.println(person);

 58 

 59         // 使用query对象查询列表

 60         query = new Query(Criteria.where("age").lt(30)).// age小于30

 61                 with(new Sort(Direction.ASC, "age"));// age 升序

 62         // query.with(Pageable );//可分页查询

 63 

 64         List<Person> list = this.mongoTemplate.find(query.with(new Sort(Direction.ASC, "age")), Person.class);

 65         System.out.println(list);

 66     }

 67     

 68     @Test

 69     public void testUpdateDoc() {

 70         // age为34的person,age加1

 71         Query query = new Query(Criteria.where("id").is(1011));

 72         Update update = new Update().inc("age", 1);

 73         Person p = this.mongoTemplate.findAndModify(query, update, Person.class);

 74         System.out.println(p);

 75 

 76         p = this.mongoTemplate.findAndModify(query, update, new FindAndModifyOptions().returnNew(true), Person.class);// returnNew(true)将更新后的对象返回

 77         System.out.println(p);

 78 

 79         // 将age为21的name改成zhangsan22,如果有多个age为21的,则只改变第一个

 80         query = new Query(Criteria.where("age").is(21));

 81         update = new Update().set("name", "zhangsan22");

 82         WriteResult result = this.mongoTemplate.updateFirst(query, update, Person.class);

 83         System.out.println(result);

 84 

 85         // 将age为21的name改成zhangsan22,如果有多个age为21的,全部更新

 86         result = mongoTemplate.upsert(query, update, Person.class);

 87         System.out.println(result);

 88     }

 89     

 90     

 91     @Test

 92     public void testRemoveDoc(){

 93         Query query = new Query(Criteria.where("age").is(35));

 94         // mongoTemplate.findAndRemove(query, Person.class);//删除文档

 95         // mongoTemplate.findAndRemove(query, Person.class,

 96         // collectionName)//删除指定集合内的文档

 97         Person person = this.mongoTemplate.findOne(query, Person.class);

 98         WriteResult result = this.mongoTemplate.remove(person);

 99         System.out.println(result);

100         this.mongoTemplate.remove(query, Person.class);// 根据query对象删除文档

101 

102         // mongoTemplate.remove(person, collection);//从指定的集合中删除文档

103         // mongoTemplate.remove(query, collectionName);//从指定的集合中根据query对象删除文档

104         // mongoTemplate.remove(query, entityClass, collectionName)//从指定的集合中根据query对象和class类型删除文档

105 

106     }

107     

108 }

你可能感兴趣的:(mongodb)