Spring 访问 MongoDB
# Spring 访问 MongoDB
# 简介
MongoDB (opens new window) 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。MongoDB 将数据存储为一个文档,数据结构由键值对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。
在 Spring 中,spring-data-mongodb (opens new window) 项目对访问 MongoDB (opens new window) 进行了 API 封装,提供了便捷的访问方式。 Spring Data MongoDB 的核心是一个以 POJO 为中心的模型,用于与 MongoDB DBCollection
交互并轻松编写 Repository
样式的数据访问层。
spring-boot (opens new window) 项目中的子模块 spring-boot-starter-data-mongodb (opens new window) 基于 spring-data-mongodb (opens new window) 项目,做了二次封装,大大简化了 MongoDB 的相关配置。
# Spring Boot 快速入门
# 引入依赖
在 pom.xml 中引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
# 数据源配置
spring.data.mongodb.host = localhost
spring.data.mongodb.port = 27017
spring.data.mongodb.database = test
spring.data.mongodb.username = root
spring.data.mongodb.password = root
# 定义实体
定义一个具有三个属性的 Customer
类:id
、firstName
和 lastName
import org.springframework.data.annotation.Id;
public class Customer {
@Id
public String id;
public String firstName;
public String lastName;
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);
}
}
spring-data-mongodb (opens new window) 会将 Customer
类映射到一个名为 customer
的集合中。如果要更改集合的名称,可以在类上使用 @Document
注解。
# 创建 Repository
spring-data-mongodb (opens new window) 继承了 Spring Data Commons (opens new window) 项目的能力,所以可以使用其通用 API——Repository
。
先定义一个 CustomerRepository
类,继承 MongoRepository
接口,并指定其泛型参数:Customer
和 String
。MongoRepository 接口支持多种操作,包括 CRUD 和分页查询。在下面的例子中,定义了两个查询方法:
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface CustomerRepository extends MongoRepository<Customer, String> {
Customer findByFirstName(String firstName);
List<Customer> findByLastName(String lastName);
}
# 创建 Application
创建一个 Spring Boot 的启动类 Application,并在启动的 main 方法中使用 CustomerRepository
实例访问 MongoDB。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DataMongodbApplication implements CommandLineRunner {
@Autowired
private CustomerRepository repository;
public static void main(String[] args) {
SpringApplication.run(DataMongodbApplication.class, args);
}
@Override
public void run(String... args) {
repository.deleteAll();
// save a couple of customers
repository.save(new Customer("Alice", "Smith"));
repository.save(new Customer("Bob", "Smith"));
// fetch all customers
System.out.println("Customers found with findAll():");
System.out.println("-------------------------------");
for (Customer customer : repository.findAll()) {
System.out.println(customer);
}
System.out.println();
// 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("Smith")) {
System.out.println(customer);
}
}
}
运行 DataMongodbApplication
的 main 方法后,输出类似如下类容:
Customers found with findAll():
-------------------------------
Customer(id=63d6157b265e7c5e48077f63, firstName=Alice, lastName=Smith)
Customer(id=63d6157b265e7c5e48077f64, firstName=Bob, lastName=Smith)
Customer found with findByFirstName('Alice'):
--------------------------------
Customer(id=63d6157b265e7c5e48077f63, firstName=Alice, lastName=Smith)
Customers found with findByLastName('Smith'):
--------------------------------
Customer(id=63d6157b265e7c5e48077f63, firstName=Alice, lastName=Smith)
Customer(id=63d6157b265e7c5e48077f64, firstName=Bob, lastName=Smith)
# 示例源码
更多 Spring 访问 MongoDB 示例请参考:MongoDB 示例源码 (opens new window)
# 参考资料
- MongoDB 官网 (opens new window)
- MongoDB Github (opens new window)
- MongoDB 官方免费教程 (opens new window)
- spring-data-mongodb Github (opens new window)
- Spring Data MongoDB 官方文档 (opens new window)
- Spring Data 官方示例 (opens new window)
- Accessing Data with MongoDB (opens new window)
- Accessing MongoDB Data with REST (opens new window)