使用 Spring Data JDBC 與 適用於 PostgreSQL 的 Azure 資料庫

本教學示範如何使用 Spring Data JDBC,將資料儲存在 適用於 PostgreSQL 的 Azure 資料庫 資料庫中。

JDBC 是連接傳統關聯式資料庫的標準Java API。

在本教學中,我們包含兩種認證方法:Microsoft Entra 認證與 PostgreSQL 認證。 Passwordless 標籤顯示 Microsoft Entra 認證,Password 標籤顯示 PostgreSQL 認證。

Microsoft Entra 認證是一種利用 Microsoft Entra ID 定義的身份,連接 適用於 PostgreSQL 的 Azure 資料庫 的機制。 透過 Microsoft Entra 認證,您可以集中管理資料庫使用者身份及其他 Microsoft 服務,簡化權限管理。

PostgreSQL 驗證會使用儲存在 PostgreSQL 中的帳戶。 如果您選擇使用密碼作為帳戶的認證,則這些認證會儲存在 user 資料表中。 由於這些密碼會儲存在 PostgreSQL 中,因此您必須自行管理密碼的輪替。

必要條件

  • PostgreSQL 命令行用戶端

  • 如果您沒有 Spring Boot 應用程式,請使用 Spring Initializr 建立 Maven 專案。 請務必選擇 Maven Project,並在 Dependencies 中加入 Spring WebSpring Data JDBC 以及 PostgreSQL Driver相性,然後選擇Java版本 8 或更高版本。

請參閱範例應用程式

在本教學課程中,您將撰寫範例應用程式的程序代碼。 如果你想更快,這個應用程式已經編碼好,且在 https://github.com/Azure-Samples/quickstart-spring-data-jdbc-postgresql 上有提供。

設定 PostgreSQL 伺服器的防火牆規則

適用於 PostgreSQL 的 Azure 資料庫 的實例預設是安全的。 其防火牆不允許任何連入連線。

若要能夠使用您的資料庫,請開啟伺服器的防火牆,以允許本機 IP 位址存取資料庫伺服器。 欲了解更多資訊,請參閱適用於 PostgreSQL 的 Azure 資料庫 - Flexible Server中的防火牆規則。

如果你是從 Windows 電腦上的 Windows 子系統 Linux 版(WSL)連接到 PostgreSQL 伺服器,你需要在防火牆上新增 WSL 主機 ID。

建立 PostgreSQL 非系統管理員使用者並授與權限

接下來,建立非系統管理員使用者,並授與資料庫的所有權限。

您可以使用下列方法來建立使用無密碼連線的非系統管理員使用者。

  1. 請使用以下指令安裝Azure CLI的 Service Connector 無密碼擴充功能:

     az extension add --name serviceconnector-passwordless --upgrade
    
  2. 請使用以下指令建立 Microsoft Entra 非管理員使用者:

      az connection create postgres-flexible \
           --resource-group <your_resource_group_name> \
           --connection postgres_conn \
           --target-resource-group <your_resource_group_name> \
           --server postgresqlflexibletest \
           --database demo \
           --user-account \
           --query authInfo.userName \
           --output tsv
    

    當命令完成時,記下主控台輸出中的用戶名稱。

將資料儲存於 適用於 PostgreSQL 的 Azure 資料庫

現在你已經有一個 適用於 PostgreSQL 的 Azure 資料庫 Flexible Server 實例,可以用 Spring Cloud Azure 來儲存資料。

要安裝 Spring Cloud Azure Starter JDBC PostgreSQL 模組,請在您的 pom.xml 檔案中新增以下相依關係:

  • Spring Cloud Azure 物料清單(BOM):

    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.azure.spring</groupId>
          <artifactId>spring-cloud-azure-dependencies</artifactId>
          <version>7.2.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    

    注意

    如果你用的是 Spring Boot 4.0.x,記得把版本設 spring-cloud-azure-dependencies7.2.0.

    如果你用的是 Spring Boot 3.5.x,記得把版本設 spring-cloud-azure-dependencies6.2.0

    如果你使用的是 Spring Boot 3.1.x-3.5.x,記得把版本設 spring-cloud-azure-dependencies5.25.0.

    如果您使用 Spring Boot 2.x,請務必將 spring-cloud-azure-dependencies 版本設定為 4.20.0

    此材料帳單 (BOM) 應該在 <dependencyManagement> 檔案的 區段中設定。 這可確保所有 Spring Cloud Azure 相依性均使用相同版本。

    欲了解更多關於本物料清單所用版本的資訊,請參見 Spring Cloud Azure 應該使用哪個版本

  • Spring Cloud Azure Starter JDBC PostgreSQL 工件:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter-jdbc-postgresql</artifactId>
    </dependency>
    

注意

自 版本 4.5.0以來,已支援無密碼連線。

設定 Spring Boot 使用 適用於 PostgreSQL 的 Azure 資料庫

若要使用 Spring Data JDBC 從 適用於 PostgreSQL 的 Azure 資料庫 儲存資料,請依照以下步驟設定應用程式:

  1. 請透過在你的 application.properties 設定檔中新增以下屬性來設定適用於 PostgreSQL 的 Azure 資料庫憑證。

    logging.level.org.springframework.jdbc.core=DEBUG
    
    spring.datasource.url=jdbc:postgresql://postgresqlflexibletest.postgres.database.azure.com:5432/demo?sslmode=require
    spring.datasource.username=<your_postgresql_ad_non_admin_username>
    spring.datasource.azure.passwordless-enabled=true
    
    spring.sql.init.mode=always
    

    警告

    組態屬性 spring.sql.init.mode=always 表示 Spring Boot 會在每次啟動伺服器時,使用 您下次建立的schema.sql 檔案,自動產生資料庫架構。 這項功能非常適合用於測試,但請記住,它會在每次重新啟動時刪除您的數據,因此您不應該在生產環境中使用它。

  • 如果沒有,請建立一個名為 postgresqlsingletest 的適用於 PostgreSQL 的 Azure 資料庫單一伺服器實例,以及一個名為 demo 的資料庫。 相關說明請參見 快速入門:使用 Azure portal 建立 適用於 PostgreSQL 的 Azure 資料庫 伺服器。

請參閱範例應用程式

在本文中,您將撰寫範例應用程式的程序代碼。 如果你想更快,這個應用程式已經編碼好,且在 https://github.com/Azure-Samples/quickstart-spring-data-jdbc-postgresql 上有提供。

設定 PostgreSQL 伺服器的防火牆規則

適用於 PostgreSQL 的 Azure 資料庫 的實例預設是安全的。 其防火牆不允許任何連入連線。

若要能夠使用您的資料庫,請開啟伺服器的防火牆,以允許本機 IP 位址存取資料庫伺服器。 欲了解更多資訊,請參閱 使用 Azure portal 建立及管理 適用於 PostgreSQL 的 Azure 資料庫 - 單一伺服器防火牆規則。

如果你是從 Windows 電腦上的 Windows 子系統 Linux 版(WSL)連接到 PostgreSQL 伺服器,你需要在防火牆上新增 WSL 主機 ID。

建立 PostgreSQL 非系統管理員使用者並授與權限

接下來,建立非系統管理員使用者,並授與資料庫的所有權限。

您可以使用下列方法來建立使用無密碼連線的非系統管理員使用者。

  1. 請使用以下指令安裝Azure CLI的 Service Connector 無密碼擴充功能:

     az extension add --name serviceconnector-passwordless --upgrade
    
  2. 請使用以下指令建立 Microsoft Entra 非管理員使用者:

      az connection create postgres \
           --resource-group <your_resource_group_name> \
           --connection postgres_conn \
           --target-resource-group <your_resource_group_name> \
           --server postgresqlsingletest \
           --database demo \
           --user-account \
           --query authInfo.userName \
           --output tsv
    

    當命令完成時,記下主控台輸出中的用戶名稱。

將資料儲存於 適用於 PostgreSQL 的 Azure 資料庫

現在你已經有一個 適用於 PostgreSQL 的 Azure 資料庫 單伺服器實例,可以用 Spring Cloud Azure 來儲存資料。

要安裝 Spring Cloud Azure Starter JDBC PostgreSQL 模組,請在您的 pom.xml 檔案中新增以下相依關係:

  • Spring Cloud Azure 物料清單(BOM):

    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.azure.spring</groupId>
          <artifactId>spring-cloud-azure-dependencies</artifactId>
          <version>7.2.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    

    注意

    如果你用的是 Spring Boot 4.0.x,記得把版本設 spring-cloud-azure-dependencies7.2.0.

    如果你用的是 Spring Boot 3.5.x,記得把版本設 spring-cloud-azure-dependencies6.2.0

    如果你使用的是 Spring Boot 3.1.x-3.5.x,記得把版本設 spring-cloud-azure-dependencies5.25.0.

    如果您使用 Spring Boot 2.x,請務必將 spring-cloud-azure-dependencies 版本設定為 4.20.0

    此材料帳單 (BOM) 應該在 <dependencyManagement> 檔案的 區段中設定。 這確保所有 Spring Cloud Azure 相依性都使用相同的版本。

    欲了解更多關於本物料清單所用版本的資訊,請參見 Spring Cloud Azure 應該使用哪個版本

  • Spring Cloud Azure Starter JDBC PostgreSQL 工件:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter-jdbc-postgresql</artifactId>
    </dependency>
    

注意

自 版本 4.5.0以來,已支援無密碼連線。

設定 Spring Boot 使用 適用於 PostgreSQL 的 Azure 資料庫

若要使用 Spring Data JDBC 從 適用於 PostgreSQL 的 Azure 資料庫 儲存資料,請依照以下步驟設定應用程式:

  1. 請透過在你的 application.properties 設定檔中新增以下屬性來設定適用於 PostgreSQL 的 Azure 資料庫憑證。

    logging.level.org.springframework.jdbc.core=DEBUG
    
    spring.datasource.url=jdbc:postgresql://postgresqlsingletest.postgres.database.azure.com:5432/demo?sslmode=require
    spring.datasource.username=<your_postgresql_ad_non_admin_username>@postgresqlsingletest
    spring.datasource.azure.passwordless-enabled=true
    
    spring.sql.init.mode=always
    

    警告

    組態屬性 spring.sql.init.mode=always 表示 Spring Boot 會在每次啟動伺服器時,使用 您下次建立的schema.sql 檔案,自動產生資料庫架構。 這項功能非常適合用於測試,但請記住,它會在每次重新啟動時刪除您的數據,因此您不應該在生產環境中使用它。

  1. 建立 src/main/resources/schema.sql 組態檔來設定資料庫架構,然後新增下列內容。

    DROP TABLE IF EXISTS todo;
    CREATE TABLE todo (id SERIAL PRIMARY KEY, description VARCHAR(255), details VARCHAR(4096), done BOOLEAN);
    
  1. 建立一個新的 Todo Java 類別。 這個類別是一個映射到 todo 數據表的領域模型,該數據表將由 Spring Boot 自動建立。 下列程式碼忽略了 getterssetters 這些方法。

    import org.springframework.data.annotation.Id;
    
    public class Todo {
    
        public Todo() {
        }
    
        public Todo(String description, String details, boolean done) {
            this.description = description;
            this.details = details;
            this.done = done;
        }
    
        @Id
        private Long id;
    
        private String description;
    
        private String details;
    
        private boolean done;
    
    }
    
  2. 編輯啟動類別檔案以顯示下列內容。

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.context.event.ApplicationReadyEvent;
    import org.springframework.context.ApplicationListener;
    import org.springframework.context.annotation.Bean;
    import org.springframework.data.repository.CrudRepository;
    
    import java.util.stream.Stream;
    
    @SpringBootApplication
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    
        @Bean
        ApplicationListener<ApplicationReadyEvent> basicsApplicationListener(TodoRepository repository) {
            return event->repository
                .saveAll(Stream.of("A", "B", "C").map(name->new Todo("configuration", "congratulations, you have set up correctly!", true)).toList())
                .forEach(System.out::println);
        }
    
    }
    
    interface TodoRepository extends CrudRepository<Todo, Long> {
    
    }
    

    提示

    在本教學課程中,組態或程式代碼中沒有任何驗證作業。 不過,連接 Azure 服務需要驗證。 要完成驗證,你需要使用 Azure Identity。 Spring Cloud Azure 使用 DefaultAzureCredential,這是 Azure Identity 函式庫提供的,幫助你在不更改程式碼的情況下取得憑證。

    DefaultAzureCredential 支援多種驗證方法,並在執行階段判斷應使用的方法。 這種方法可讓您的應用程式在不同的環境中使用不同的驗證方法(例如本機和生產環境),而不需要實作環境特定的程序代碼。 如需詳細資訊,請參閱 DefaultAzureCredential

    要在本地開發環境中完成認證,你可以使用 Azure CLI、Visual Studio Code、PowerShell 或其他方法。 欲了解更多資訊,請參閱 Azure Java開發環境中的認證。 在 Azure 主機環境中完成認證,我們建議使用使用者指派的管理身份。 欲了解更多資訊,請參閱 Azure資源的受管理身份是什麼?

  3. 啟動應用程式。 應用程式會將資料儲存至資料庫。 您會看到類似下列範例的記錄:

    2023-02-01 10:22:36.701 DEBUG 7948 --- [main] o.s.jdbc.core.JdbcTemplate : Executing prepared SQL statement [INSERT INTO todo (description, details, done) VALUES (?, ?, ?)]    
    com.example.demo.Todo@4bdb04c8
    

部署到 Azure Spring 應用程式

現在您已在本機執行 Spring Boot 應用程式,現在可以將其移至生產環境。 Azure Spring 應用程式 讓 Spring Boot 應用程式部署到 Azure 變得簡單,無需修改程式碼。 服務會管理 Spring 應用程式的基礎結構,讓開發人員可以專注於處理程式碼。 Azure Spring 應用程式 提供生命週期管理,包含全面的監控與診斷、組態管理、服務發現、CI/CD 整合、藍綠部署等多項功能。 要將您的應用程式部署到 Azure Spring 應用程式,請參見 將您的第一個應用程式部署至 Azure Spring 應用程式

下一步