Spring Boot MongoDB
最后修改于 2023 年 7 月 16 日
Spring Boot MongoDB 教程演示了如何在 Spring Boot 框架中访问 MongoDB 中的数据。
Spring 是一个流行的 Java 应用程序框架,而 Spring Boot 是 Spring 的一个演进,它有助于轻松创建独立的、生产级别的基于 Spring 的应用程序。
MongoDB
MongoDB 是一个 NoSQL 跨平台面向文档的数据库。它是目前最流行的数据库之一。MongoDB 由 MongoDB Inc. 开发,并作为免费和开源软件发布。
Spring Data MongoDB 项目提供了与 MongoDB 文档数据库的集成。
安装 MongoDB
以下命令可用于在基于 Debian 的 Linux 上安装 MongoDB。
$ sudo apt-get install mongodb
该命令安装 MongoDB 附带的必要软件包。
$ sudo service mongodb status mongodb start/running, process 975
使用 sudo service mongodb status 命令,我们检查 mongodb 服务器的状态。
$ sudo service mongodb start mongodb start/running, process 6448
mongodb 服务器通过 sudo service mongodb start 命令启动。
Spring Boot MongoDB 示例
在下面的示例中,我们创建了一个简单的 Spring Boot 应用程序,它使用 MongoDB 数据库。请注意,默认情况下,在没有任何特定配置的情况下,Spring Boot 尝试连接到本地托管的 MongoDB 实例,使用 test 数据库名称。
pom.xml
src
├───main
│ ├───java
│ │ └───com
│ │ └───zetcode
│ │ │ Application.java
│ │ │ MyRunner.java
│ │ ├───model
│ │ │ Country.java
│ │ └───repository
│ │ CountryRepository.java
│ └───resources
│ application.properties
└───test
└───java
└───com
└───zetcode
MongoTest.java
这是 Spring 应用程序的项目结构。
<?xml version="1.0" encoding="UTF-8"?>
<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.zetcode</groupId>
<artifactId>springbootmongodb</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.7</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.7</version>
</plugin>
</plugins>
</build>
</project>
这是 Maven 的 pom.xml 文件。
Spring Boot starters 是一组方便的依赖描述符,极大地简化了 Maven 配置。 spring-boot-starter-parent 包含 Spring Boot 应用程序的一些常见配置。 spring-boot-starter-data-mongodb 是一个用于使用面向文档的 MongoDB 数据库和 Spring Data MongoDB 的 starter。 spring-boot-starter-test 是一个用于使用 JUnit、Hamcrest 和 Mockito 等库测试 Spring Boot 应用程序的 starter。
spring-boot-maven-plugin 在 Maven 中提供 Spring Boot 支持,允许我们打包可执行的 JAR 或 WAR 归档文件。它的 spring-boot:run 目标运行 Spring Boot 应用程序。
spring.main.banner-mode=off logging.level.org.springframework=ERROR
在 application.properties 中,我们关闭 Spring Boot banner 并设置日志属性。默认情况下,Spring Boot 尝试连接到本地托管的 MongoDB 实例,使用 test 数据库。
# mongodb spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 spring.data.mongodb.database=testdb
如果我们想配置 MongoDB,我们可以设置相应的属性。
package com.zetcode.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.Objects;
@Document
public class Country {
@Id
private String id;
private String name;
private int population;
public Country(String name, int population) {
this.name = name;
this.population = population;
}
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 getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Country country = (Country) o;
return population == country.population &&
Objects.equals(id, country.id) &&
Objects.equals(name, country.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name, population);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Country{");
sb.append("id='").append(id).append('\'');
sb.append(", name='").append(name).append('\'');
sb.append(", population=").append(population);
sb.append('}');
return sb.toString();
}
}
这是 Country bean,它具有三个属性:id、name 和 population。
@Document
public class Country {
该 bean 使用可选的 @Document 注解进行修饰。
@Id private String id;
id 使用 @Id 注解进行修饰。 Spring 会自动为新生成的国家对象生成一个新的 id。
package com.zetcode.repository;
import com.zetcode.model.Country;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface CountryRepository extends MongoRepository<Country, String> {
}
通过继承 MongoRepository,我们开箱即用地获得许多操作,包括标准的 CRUD 操作。
package com.zetcode;
import com.zetcode.model.Country;
import com.zetcode.repository.CountryRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class MyRunner implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(MyRunner.class);
@Autowired
private CountryRepository repository;
@Override
public void run(String... args) throws Exception {
repository.deleteAll();
repository.save(new Country("China", 1382050000));
repository.save(new Country("India", 1313210000));
repository.findAll().forEach((country) -> {
logger.info("{}", country);
});
}
}
我们有一个命令行运行器。在其 run 方法中,我们访问 MongoDB。
@Autowired private CountryRepository repository;
CountryRepository 通过 @Autowired 注解注入。
repository.deleteAll();
如果存在,我们使用 deleteAll 删除所有国家。
repository.save(new Country("China", 1382050000));
我们使用 save 保存一个国家。
repository.findAll().forEach((country) -> {
logger.info("{}", country);
});
我们使用 findAll 方法遍历数据库中的所有国家。
package com.zetcode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
此代码设置了 Spring Boot 应用程序。
package com.zetcode;
import com.zetcode.model.Country;
import com.zetcode.repository.CountryRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Example;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Optional;
import static junit.framework.TestCase.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MongoTest {
@Autowired
private CountryRepository repository;
private static final int NUMBER_OF_COUNTRIES = 6;
@Before
public void init() {
repository.deleteAll();
repository.save(new Country("China", 1382050000));
repository.save(new Country("India", 1313210000));
repository.save(new Country("USA", 324666000));
repository.save(new Country("Indonesia", 260581000));
repository.save(new Country("Brazil", 207221000));
repository.save(new Country("Pakistan", 196626000));
}
@Test
public void countAllCountries() {
var countries = repository.findAll();
assertEquals(NUMBER_OF_COUNTRIES, countries.size());
}
@Test
public void countOneCountry() {
Example<Country> example = Example.of(new Country("China", 1382050000));
assertThat(repository.count(example)).isEqualTo(1L);
}
@Test
public void setsIdOnSave() {
Country nigeria = repository.save(new Country("Nigeria", 186988000));
assertThat(nigeria.getId()).isNotNull();
}
@Test
public void findOneCountry() {
Example<Country> example = Example.of(new Country("India", 1313210000));
Optional<Country> country = repository.findOne(example);
assertThat(country.get().getName()).isEqualTo("India");
}
}
我们有四个测试方法。
@Before
public void init() {
repository.deleteAll();
repository.save(new Country("China", 1382050000));
repository.save(new Country("India", 1313210000));
repository.save(new Country("USA", 324666000));
repository.save(new Country("Indonesia", 260581000));
repository.save(new Country("Brazil", 207221000));
repository.save(new Country("Pakistan", 196626000));
}
在 init 方法中,我们保存六个国家。
@Test
public void countAllCountries() {
var countries = repository.findAll();
assertEquals(NUMBER_OF_COUNTRIES, countries.size());
}
我们测试数据库中是否有六个国家。
@Test
public void countOneCountry() {
Example<Country> example = Example.of(new Country("China", 1382050000));
assertThat(repository.count(example)).isEqualTo(1L);
}
此方法测试数据库中只有一个中国。
@Test
public void setsIdOnSave() {
Country nigeria = repository.save(new Country("Nigeria", 186988000));
assertThat(nigeria.getId()).isNotNull();
}
我们测试当我们保存一个新国家时,自动生成的 id 不等于 null。
@Test
public void findOneCountry() {
Example<Country> example = Example.of(new Country("India", 1313210000));
Optional<Country> country = repository.findOne(example);
assertThat(country.get().getName()).isEqualTo("India");
}
我们测试 findOne 方法找到一个国家,即印度。
在本文中,我们学习了如何在 Spring Boot 应用程序中使用 MongoDB。