SpringDataMongoDB介绍(二)-MongoOperations介绍
MongoOperations是一个很强大的接口,有了这个接口,基本上什么都搞定了。
其介绍
Interface that specifies a basic set of MongoDB operations. Implemented by {@link MongoTemplate}. Not often used but a useful option for extensibility and testability (as it can be easily mocked, stubbed, or be the target of a JDK proxy
直接上代码
实体类
package com.chzhao.mongodbtest;
import java.util.Date;
import org.springframework.data.annotation.Id;
public class Person {
public Person(String name, int age, Date birth) {
this.name = name;
this.age = age;
this.birth = birth;
}
private Date birth;
@Id
private String id;
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
private String name;
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;
}
private int age;
}
操作类
package com.chzhao.mongodbtest;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import com.mongodb.Mongo;
public class MongoApp {
private static final Log log = LogFactory.getLog(MongoApp.class);
public static void main(String[] args) throws Exception {
MongoOperations mongoOps = new MongoTemplate(new Mongo(), "zch");
mongoOps.dropCollection(Person.class);
mongoOps.remove(new Query(where("name").is("zhao")), Person.class);
DateTime zhaoBirth = new DateTime(1985, 12, 13, 18, 23, 55);
DateTime liangBirth = new DateTime(1986, 12, 13, 18, 23, 55);
mongoOps.insert(new Person("zhao", 34, zhaoBirth.toDate()));
mongoOps.insert(new Person("liang", 24, liangBirth.toDate()));
List<Person> pList = mongoOps.find(new Query(where("name").is("zhao")),
Person.class);
for (Person p : pList) {
log.info(p.getName() + p.getAge());
}
DateTime someday = new DateTime(1986, 1, 13, 18, 23, 55);
List<Person> pList1 = mongoOps.find(new Query(where("birth").lt(someday)), Person.class);
for (Person p : pList1) {
log.info(p.getName() + p.getAge());
}
}
}
这个Query类似lambda表达式,能做很多事情,很赞。