Share via


搭配 Azure SQL 資料庫 使用 Spring Data JDBC

本教學課程示範如何使用 Spring Data JDBC 將數據儲存在 Azure SQL 資料庫

JDBC 是連線到傳統關係資料庫的標準 Java API。

在本教學課程中,我們包含兩個驗證方法:Microsoft Entra 驗證和 SQL 資料庫 驗證。 [無密碼] 索引標籤會顯示 [Microsoft Entra 驗證],[密碼] 索引標籤會顯示 SQL 資料庫 驗證。

Microsoft Entra 驗證是一種機制,可使用 Microsoft Entra 識別碼中定義的身分識別連線到適用於 SQL 資料庫 的 Azure 資料庫。 透過 Microsoft Entra 驗證,您可以在集中的位置管理資料庫使用者的身分識別和其他 Microsoft 服務,從而簡化權限管理。

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

必要條件

  • sqlcmd 公用程式

  • ODBC Driver 17 或 18。

  • 如果您沒有 Azure SQL Server 實例,請建立名為 sqlservertest 的 Azure SQL Server 實例,以及名為 demo的資料庫。 如需指示,請參閱快速入門:建立單一資料庫 - Azure SQL 資料庫

  • 如果您沒有 Spring Boot 應用程式,請使用 Spring Initializr 建立 Maven 專案。 請務必選取 Maven 專案,然後在 [相依性] 底下新增 Spring WebSpring Data JDBCMS SQL Server 驅動程式相依性,然後選取 [Java 第 8 版或更新版本]。

請參閱範例應用程式

在本教學課程中,您將撰寫範例應用程式的程序代碼。 如果您想要更快速地執行,此應用程式已編碼,且可在取得 https://github.com/Azure-Samples/quickstart-spring-data-jdbc-sql-server

設定 Azure SQL 資料庫伺服器的防火牆規則

Azure SQL 資料庫執行個體預設受到保護。 它們具有不允許任何連入連線的防火牆。

若要能夠使用您的資料庫,請開啟伺服器的防火牆,以允許本機 IP 位址存取資料庫伺服器。 如需詳細資訊,請參閱教學課程:保護 Azure SQL 資料庫 中的資料庫。

如果您要從 Windows 電腦上的 Windows 子系統 Linux 版 (WSL) 連線到 Azure SQL 資料庫 伺服器,您必須將 WSL 主機標識元新增至防火牆。

建立 SQL Database 非系統管理員使用者並授與許可權

此步驟會建立非系統管理員使用者,並將資料庫的所有許可權 demo 授與其。

若要使用無密碼連線,請參閱教學課程:保護 Azure SQL 資料庫 中的資料庫,或使用 Service 連線 or 為 Azure SQL 資料庫 伺服器建立 Microsoft Entra 系統管理員使用者,如下列步驟所示:

  1. 首先,安裝 Azure CLI 的服務 連線 或無密碼擴充功能:

    az extension add --name serviceconnector-passwordless --upgrade
    
  2. 然後,使用下列命令來建立 Microsoft Entra 非系統管理員使用者:

    az connection create sql \
        --resource-group <your-resource-group-name> \
        --connection sql_conn \
        --target-resource-group <your-resource-group-name> \
        --server sqlservertest \
        --database demo \
        --user-account \
        --query authInfo.userName \
        --output tsv
    

您建立的 Microsoft Entra 系統管理員是 SQL 資料庫管理員使用者,因此您不需要建立新的使用者。

重要

Azure SQL 資料庫無密碼連線需要將 MS SQL Server 驅動程式 升級至版本或更新版本 12.1.0 。 連接選項位於 authentication=DefaultAzureCredential 版本 12.1.0authentication=ActiveDirectoryDefault 版本中 12.2.0

從 Azure SQL 資料庫 儲存數據

使用 Azure SQL 資料庫 實體,您可以使用 Spring Cloud Azure 來儲存數據。

若要安裝 Spring Cloud Azure Starter 模組,請將下列相依性新增至您的 pom.xml 檔案:

  • Spring Cloud Azure 材料帳單(BOM):

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

    注意

    如果您使用 Spring Boot 2.x,請務必將 spring-cloud-azure-dependencies 版本設定為 4.18.0。 此材料帳單 (BOM) 應該在<dependencyManagement>pom.xml檔案的 區段中設定。 這可確保所有 Spring Cloud Azure 相依性都使用相同的版本。 如需此 BOM 所用版本的詳細資訊,請參閱 應該使用哪個版本的 Spring Cloud Azure。

  • Spring Cloud Azure 入門成品:

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

    注意

    由於這是相依性,因此應該在 <dependencies> pom.xml區段中新增它。 此處未設定其版本,因為其是由我們先前新增的 BOM 所管理。

設定 Spring Boot 以使用 Azure SQL 資料庫

若要使用 Spring Data JDBC 從 Azure SQL 資料庫 儲存數據,請遵循下列步驟來設定應用程式:

  1. 在 application.properties 組態檔中設定 Azure SQL 資料庫 認證。

    logging.level.org.springframework.jdbc.core=DEBUG
    
    spring.datasource.url=jdbc:sqlserver://sqlservertest.database.windows.net:1433;databaseName=demo;authentication=DefaultAzureCredential;
    
    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 INT IDENTITY PRIMARY KEY, description VARCHAR(255), details VARCHAR(4096), done BIT);
    
  1. 建立新的 Todo Java 類別。 這個類別是對應到 Spring Boot 自動建立之數據表的 todo 網域模型。 下列程式代碼會 getters 忽略和 setters 方法。

    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 身分識別連結庫會提供它來協助您取得認證,而不需要變更任何程序代碼。

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

    若要在本機開發環境中完成驗證,您可以使用 Azure CLI、Visual Studio Code、PowerShell 或其他方法。 如需詳細資訊,請參閱 Java 開發環境中的 Azure 驗證。 若要在 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 Apps

現在您已在本機執行 Spring Boot 應用程式,現在可以將其移至生產環境。 Azure Spring Apps 可讓您輕鬆地將 Spring Boot 應用程式部署至 Azure,而不需要變更任何程式代碼。 服務會管理 Spring 應用程式的基礎結構,讓開發人員可以專注於處理程式碼。 Azure Spring 應用程式提供生命週期管理,使用全方位的監視和診斷、組態管理、服務探索、持續整合與持續傳遞的整合、藍綠部署等等。 若要將應用程式部署至 Azure Spring Apps,請參閱 將第一個應用程式部署至 Azure Spring Apps

下一步