<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # Spring Boot MongoDB 教程 > 原文: [http://zetcode.com/springboot/mongodb/](http://zetcode.com/springboot/mongodb/) 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。 ```java $ sudo apt-get install mongodb ``` 該命令將安裝 MongoDB 隨附的必要包。 ```java $ sudo service mongodb status mongodb start/running, process 975 ``` 使用`sudo service mongodb status`命令,我們檢查`mongodb`服務器的狀態。 ```java $ sudo service mongodb start mongodb start/running, process 6448 ``` `mongodb`服務器由`sudo service mongodb start`命令啟動。 ## Spring Boot MongoDB 示例 在以下示例中,我們創建一個使用 MongoDB 數據庫的簡單 Spring Boot 應用。 請注意,默認情況下,沒有任何特定配置,Spring Boot 會嘗試使用`test`數據庫名稱連接到本地托管的 MongoDB 實例。 ```java 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 應用的項目結構。 `pom.xml` ```java <?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>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.1.RELEASE</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> </plugin> </plugins> </build> </project> ``` 這是 Maven `pom.xml`文件。 Spring Boot 啟動器是一組方便的依賴項描述符,可以極大地簡化 Maven 配置。 `spring-boot-starter-parent`具有 Spring Boot 應用的一些常用配置。 `spring-boot-starter-data-mongodb`是使用 MongoDB 面向文檔的數據庫和 Spring Data MongoDB 的入門。 `spring-boot-starter-test`是使用包含 JUnit,Hamcrest 和 Mockito 的庫測試 Spring Boot 應用的入門程序。 在`spring-boot-maven-plugin`提供了 Maven 的 Spring Boot 支持,使我們能夠打包可執行的 JAR 或 WAR 檔案。 它的`spring-boot:run`目標運行 Spring Boot 應用。 `resources/application.properties` ```java spring.main.banner-mode=off logging.level.org.springframework=ERROR ``` 在`application.properties`中,我們打開 Spring Boot 橫幅并設置日志記錄屬性。 默認情況下,Spring Boot 會嘗試使用測試數據庫連接到 MongoDB 的本地托管實例。 ```java # mongodb spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 spring.data.mongodb.database=testdb ``` 如果要配置 MongoDB,可以設置相應的屬性。 `com/zetcode/model/Country.java` ```java 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`。 ```java @Document public class Country { ``` Bean 用可選的`@Document`注解修飾。 ```java @Id private String id; ``` `id`用`@Id`注解修飾。 Spring 會自動為一個新生成的國家對象生成一個新的 ID。 `com/zetcode/repository/CountryRepository.java` ```java 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 操作。 `com/zetcode/MyRunner.java` ```java 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。 ```java @Autowired private CountryRepository repository; ``` `CountryRepository`注入了`@Autowired`注解。 ```java repository.deleteAll(); ``` 如果有,我們將使用`deleteAll()`刪除所有國家。 ```java repository.save(new Country("China", 1382050000)); ``` 我們用`save()`保存一個國家。 ```java repository.findAll().forEach((country) -> { logger.info("{}", country); }); ``` 我們使用`findAll()`方法遍歷數據庫中的所有國家。 `com/zetcode/Application.java` ```java 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 應用。 `com/zetcode/MongoTest.java` ```java 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"); } } ``` 我們有四種測試方法。 ```java @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()`方法中,我們保存了六個國家。 ```java @Test public void countAllCountries() { var countries = repository.findAll(); assertEquals(NUMBER_OF_COUNTRIES, countries.size()); } ``` 我們測試數據庫中有六個國家。 ```java @Test public void countOneCountry() { Example<Country> example = Example.of(new Country("China", 1382050000)); assertThat(repository.count(example)).isEqualTo(1L); } ``` 此方法測試數據庫中只有一個中國。 ```java @Test public void setsIdOnSave() { Country nigeria = repository.save(new Country("Nigeria", 186988000)); assertThat(nigeria.getId()).isNotNull(); } ``` 我們測試了在保存新國家/地區時,自動生成的 ID 不等于`null`。 ```java @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。 您可能也對相關教程感興趣: [Spring Boot REST 數據 JPA 教程](/articles/springbootrestdatajpa/), [Spring Boot REST H2 教程](/articles/springbootresth2/), [MongoDB Java 教程](/java/mongodb/), [Java 教程](/lang/java/) 或列出[所有 Spring Boot 教程](/all/#springboot)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看