MongoDB入门(7)- SpringDataMongoDB
入门
本文介绍如何应用SpringDataMongoDB操作实体和数据库,本文只介绍最基本的例子,复杂的例子在后面的文章中介绍。
SpringDataMongoDB简介
SpringDataMongoDB是spring data的一个子项目,用来封装对MongoDB的操作,现在最新的版本是1.6.1。(截至2015年1月18日)
The Spring Data MongoDB project provides integration with the MongoDB document database. Key functional areas of Spring Data MongoDB are a POJO centric model for interacting with a MongoDB DBCollection and easily writing a Repository style data access layer.
MongoDB是一个非关系型数据库,这里不详细介绍了。
SpringDataMongoDB有以下一些特点:
- Spring configuration support using Java based @Configuration classes or an XML namespace for a Mongo driver instance and replica sets.
- MongoTemplate helper class that increases productivity performing common Mongo operations. Includes integrated object mapping between documents and POJOs.
- Exception translation into Spring's portable Data Access Exception hierarchy
- Feature Rich Object Mapping integrated with Spring's Conversion Service
- Annotation based mapping metadata but extensible to support other metadata formats
- Persistence and mapping lifecycle events
- Low-level mapping using MongoReader/MongoWriter abstractions
- Java based Query, Criteria, and Update DSLs
- Automatic implementation of Repository interfaces including support for custom finder methods.
- QueryDSL integration to support type-safe queries.
- Cross-store persistance - support for JPA Entities with fields transparently persisted/retrieved using MongoDB
- Log4j log appender
- GeoSpatial integration
- Map-Reduce integration
- JMX administration and monitoring
- CDI support for repositories
- GridFS support
实体类定义
package com.chzhao.mongodbtest;
import org.springframework.data.annotation.Id;
public class Customer {
@Id
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
private String firstName;
private String lastName;
public Customer() {}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format(
"Customer[id=%s, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}
操作类定义
package com.chzhao.mongodbtest;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface CustomerRepository extends MongoRepository<Customer, String> {
public Customer findByFirstName(String firstName);
public List<Customer> findByLastName(String lastName);
public long deleteByFirstName(String firstName);
public long countByLastName(String lastName);
}
调用方法
package com.chzhao.mongodbtest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
EnableAutoConfiguration
public class Application implements CommandLineRunner {
@Autowired
private CustomerRepository repository;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
public void run(String... args) throws Exception {
for (int i = 0; i < 10000; i++) {
repository.save(new Customer(i + "", "zhao"));
}
long cou = repository.countByLastName("zhao");
System.out.println(cou);
System.out.println("Customers found with findAll():");
System.out.println("-------------------------------");
for (Customer customer : repository.findAll()) {
System.out.println(customer);
}
System.out.println();
repository.deleteByFirstName("zhao");
// fetch an individual customer
System.out.println("Customer found with findByFirstName('Alice'):");
System.out.println("--------------------------------");
System.out.println(repository.findByFirstName("Alice"));
System.out.println("Customers found with findByLastName('Smith'):");
System.out.println("--------------------------------");
for (Customer customer : repository.findByLastName("zhao")) {
System.out.println(customer);
}
}
}
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.chzhao</groupId>
<artifactId>mongodbtest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.11.4</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.6.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<version>1.1.10.RELEASE</version>
</dependency>
</dependencies>
</project>
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表达式,能做很多事情,很赞。