一、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 主运行类
package com.yichun.test.test_yichun; import java.util.ArrayList;
import java.util.List; import javax.annotation.Resource; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.mongodb.WriteResult; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-config-mongodb.xml")
public class MongoTest extends AbstractJUnit4SpringContextTests { @Resource
private MongoTemplate mongoTemplate; @Test
public void testAddDoc() {
Person p = new Person("Joe", 34);
Person p2 = new Person("1001", "Joe", 34);
Person p11 = new Person("1011", "zhangsan", 20);
Person p12 = new Person("1012", "zhangsan2", 21);
Person p13 = new Person("1013", "zhangsan3", 23);
List<Person> list = new ArrayList<Person>();
list.add(p11);
list.add(p12);
list.add(p13);
this.mongoTemplate.insert(p);// 默认保存在person集合中(与类名称一致)
this.mongoTemplate.insert(p2, "person2");// 指定保存在person2集合中
this.mongoTemplate.insertAll(list);// 默认保存在person集合中(与类名称一致)
// mongoTemplate.insert(list, collectionName);//指定保存的集合
// mongoTemplate.insert(list, Person.class);// 默认保存在person集合中(与类名称一致)
} @Test
public void testFindDoc() {
// 根据id查询,此id为mongo生成的id
Person person = this.mongoTemplate.findById("1011", Person.class);
System.out.println(person); // 使用query对象查询
Query query = new Query(Criteria.where("age").is(34));
person = this.mongoTemplate.findOne(query, Person.class);
System.out.println(person); // 使用query对象查询列表
query = new Query(Criteria.where("age").lt(30)).// age小于30
with(new Sort(Direction.ASC, "age"));// age 升序
// query.with(Pageable );//可分页查询 List<Person> list = this.mongoTemplate.find(query.with(new Sort(Direction.ASC, "age")), Person.class);
System.out.println(list);
} @Test
public void testUpdateDoc() {
// age为34的person,age加1
Query query = new Query(Criteria.where("id").is(1011));
Update update = new Update().inc("age", 1);
Person p = this.mongoTemplate.findAndModify(query, update, Person.class);
System.out.println(p); p = this.mongoTemplate.findAndModify(query, update, new FindAndModifyOptions().returnNew(true), Person.class);// returnNew(true)将更新后的对象返回
System.out.println(p); // 将age为21的name改成zhangsan22,如果有多个age为21的,则只改变第一个
query = new Query(Criteria.where("age").is(21));
update = new Update().set("name", "zhangsan22");
WriteResult result = this.mongoTemplate.updateFirst(query, update, Person.class);
System.out.println(result); // 将age为21的name改成zhangsan22,如果有多个age为21的,全部更新
result = mongoTemplate.upsert(query, update, Person.class);
System.out.println(result);
} @Test
public void testRemoveDoc(){
Query query = new Query(Criteria.where("age").is(35));
// mongoTemplate.findAndRemove(query, Person.class);//删除文档
// mongoTemplate.findAndRemove(query, Person.class,
// collectionName)//删除指定集合内的文档
Person person = this.mongoTemplate.findOne(query, Person.class);
WriteResult result = this.mongoTemplate.remove(person);
System.out.println(result);
this.mongoTemplate.remove(query, Person.class);// 根据query对象删除文档 // mongoTemplate.remove(person, collection);//从指定的集合中删除文档
// mongoTemplate.remove(query, collectionName);//从指定的集合中根据query对象删除文档
// mongoTemplate.remove(query, entityClass, collectionName)//从指定的集合中根据query对象和class类型删除文档 } }