日期:2014-05-16 浏览次数:20469 次
<?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="localhost" port="27017"> </mongo:mongo> <bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate"> <constructor-arg ref="mongo"/> <constructor-arg name="databaseName" value="db"/> <constructor-arg name="defaultCollectionName" value="person" /> </bean> <bean id="personRepository" class="com.mongo.repository.PersonRepository"> <property name="mongoTemplate" ref="mongoTemplate"></property> </bean> </beans>
package com.mongo.entity; public class Person { private String id; private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public Person(){ } public Person(String id, String name, int age) { this.id = id; this.name = name; this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person[id="+id+",name="+name+",age="+age+"]"; } }
package com.mongo.intf; import java.util.List; import com.mongo.entity.Person; public interface AbstractRepository { public void insert(Person person); public Person findOne(String id); public List<Person> findAll(); public List<Person> findByRegex(String regex); public void removeOne(String id); public void removeAll(); public void findAndModify(String id); }
package com.mongo.repository; import java.util.List; import java.util.regex.Pattern; import org.springframework.data.document.mongodb.MongoTemplate; import org.springframework.data.document.mongodb.query.Criteria; import org.springframework.data.document.mongodb.query.Query; import org.springframework.data.document.mongodb.query.Update; import com.mongo.entity.Person; import com.mongo.intf.AbstractRepository; public class PersonRepository implements AbstractRepository{ private MongoTemplate mongoTemplate; @Override public List<Person> findAll() { return getMongoTemplate().find(new Query(), Person.class); } @Override public void findAnd