Spring Data JPA – 在沒有數據庫的情況下運行應用程序
一、概述
在本教程中,我們將學習如何在沒有運行數據庫的情況下啟動 Spring Boot 應用程序。
默認情況下,如果我們有一個包含 Spring Data JPA 的 Spring Boot 應用程序,那麼該應用程序將自動尋找創建數據庫連接。但是,在應用程序啟動時數據庫不可用的情況下,可能需要避免這種情況。
2. 設置
我們將使用一個使用 MySQL 的簡單 Spring Boot 應用程序。讓我們看一下設置應用程序的步驟。
2.1。依賴項
讓我們將Spring Data JPA starter和MySql Connector依賴項添加到pom.xml
文件中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
這會將 JPA、MySQL 連接器和 Hibernate 添加到類路徑中。
除此之外,我們希望一個任務在應用程序啟動時繼續運行。為此,讓我們將Web 啟動器添加到pom.xml
文件中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
這將在端口 8080 上啟動 Web 服務器並保持應用程序運行。
2.2.特性
在啟動應用程序之前,我們需要在application.properties
文件中設置一些強制性屬性:
spring.datasource.url=jdbc:mysql://localhost:3306/myDb
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
讓我們了解我們設置的屬性:
-
spring.datasource.url
:服務器的 URL 和數據庫的名稱。 -
spring.datasource.driver-class-name
:驅動程序類名。 MySQL 連接器提供此驅動程序。 -
spring.jpa.properties.hibernate.dialect
:我們已將其設置為 MySQL 5。這告訴 JPA 提供程序使用 MySQL 5 方言。
除此之外,我們還需要設置連接數據庫所需的用戶名和密碼:
spring.datasource.username=root
spring.datasource.password=root
2.3.啟動應用程序
如果我們啟動應用程序,我們將看到以下錯誤:
HHH000342: Could not obtain connection to query metadata
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
這是因為我們沒有在指定 URL 上運行的數據庫服務器。但是,應用程序的默認行為是執行以下兩個操作:
- JPA 嘗試連接到數據庫服務器並獲取元數據
- 如果數據庫不存在,Hibernate 將嘗試創建它。這是由於屬性
spring.jpa.hibernate.ddl-auto
設置為默認create
。
3. 在沒有數據庫的情況下運行
要在沒有數據庫的情況下繼續,我們需要通過覆蓋上面提到的兩個屬性來修復默認行為。
首先,讓我們**禁用元數據獲取**:
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false
然後,我們禁用自動數據庫創建:
spring.jpa.hibernate.ddl-auto=none
通過設置此屬性,我們禁用了數據庫的創建。因此,應用程序沒有理由創建連接。
與之前不同,現在,當我們啟動應用程序時,它啟動時沒有任何錯誤。除非操作需要與數據庫交互,否則不會啟動連接。
4。結論
在本文中,我們學習瞭如何在不需要運行數據庫的情況下啟動 Spring Boot 應用程序。
我們查看了尋找數據庫連接的應用程序的默認行為。然後我們通過覆蓋兩個屬性來修復默認行為。
與往常一樣,本文中使用的代碼示例可以在 GitHub 上找到。