本教學示範如何使用
JDBC 是連接傳統關聯式資料庫的標準Java API。
本教學中,我們包含兩種認證方法:Microsoft Entra 認證與 MySQL 認證。
Microsoft Entra 認證是一種利用 Microsoft Entra ID 中定義的身份來連接 適用於 MySQL 的 Azure 資料庫 的機制。 透過 Microsoft Entra 認證,您可以集中管理資料庫使用者身份及其他 Microsoft 服務,簡化權限管理。
MySQL 驗證會使用儲存在 MySQL 中的帳戶。 如果您選擇使用密碼作為帳戶的認證,則這些認證會儲存在 user 資料表中。 因為這些密碼會儲存在 MySQL 中,因此您必須自行管理密碼的輪替。
必要條件
Azure訂閱 - 免費創建。
Java 開發套件(JDK),版本 8 或更高。
如果您沒有 Spring Boot 應用程式,請使用 Spring Initializr 建立 Maven 專案。 請務必選擇
Maven Project ,並在Dependencies 中加入Spring Web 、Spring Data JDBC 以及 MySQL Driver 相依,然後選擇Java版本 8 或更高版本。
- 如果沒有,請建立一個名為
mysqlflexibletest的 適用於 MySQL 的 Azure 資料庫 彈性伺服器實例。 相關說明請參見 快速入門:使用 Azure 入口建立適用於 MySQL 的 Azure 資料庫 Flexible Server。 然後,建立名為demo的資料庫。 相關說明請參見 建立及管理 適用於 MySQL 的 Azure 資料庫 Flexible Server資料庫。
請參閱範例應用程式
在本教學課程中,您將撰寫範例應用程式的程序代碼。 如果你想更快,這個應用程式已經編碼好,且在 https://github.com/Azure-Samples/quickstart-spring-data-jdbc-mysql 上有提供。
設定 MySQL 伺服器的防火牆規則
適用於 MySQL 的 Azure 資料庫 實例預設是安全的。 其防火牆不允許任何連入連線。
若要能夠使用您的資料庫,請開啟伺服器的防火牆,以允許本機 IP 位址存取資料庫伺服器。 欲了解更多資訊,請參閱 使用 Azure 入口網站管理 適用於 MySQL 的 Azure 資料庫 - 彈性伺服器防火牆規則。
如果你是從 Windows 電腦上的 Windows 子系統 Linux 版(WSL)連接到 MySQL 伺服器,你需要在防火牆上加入 WSL 主機 IP 位址。
建立 MySQL 非系統管理員使用者並授與權限
此步驟會建立非系統管理員使用者,並將資料庫的所有許可權 demo 授與其。
您可以使用下列方法來建立使用無密碼連線的非系統管理員使用者。
請使用以下指令安裝Azure CLI的 Service Connector 無密碼擴充功能:
az extension add --name serviceconnector-passwordless --upgrade請使用以下指令建立 Microsoft Entra 非管理員使用者:
az connection create mysql-flexible \ --resource-group <your_resource_group_name> \ --connection mysql_conn \ --target-resource-group <your_resource_group_name> \ --server mysqlflexibletest \ --database demo \ --user-account mysql-identity-id=/subscriptions/<your_subscription_id>/resourcegroups/<your_resource_group_name>/providers/Microsoft.ManagedIdentity/userAssignedIdentities/<your_user_assigned_managed_identity_name> \ --query authInfo.userName \ --output tsv當命令完成時,記下主控台輸出中的用戶名稱。
儲存來自 Azure MySQL 資料庫的資料
現在你已經有了 適用於 MySQL 的 Azure 資料庫 Flexible Server 實例,可以用 Spring Cloud Azure 來儲存資料。
要安裝 Spring Cloud Azure Starter JDBC MySQL 模組,請在您的 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-dependencies為7.2.0.如果你用的是 Spring Boot 3.5.x,記得把版本設
spring-cloud-azure-dependencies成6.2.0。如果你使用的是 Spring Boot 3.1.x-3.5.x,記得把版本設
spring-cloud-azure-dependencies為5.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 MySQL 構件:
<dependency> <groupId>com.azure.spring</groupId> <artifactId>spring-cloud-azure-starter-jdbc-mysql</artifactId> </dependency>
注意
自 版本 4.5.0以來,已支援無密碼連線。
設定 Spring Boot 使用 Azure MySQL 資料庫
若要使用 Spring Data JDBC 從 適用於 MySQL 的 Azure 資料庫 儲存資料,請依照以下步驟設定應用程式:
請透過在你的 application.properties 設定檔中新增以下屬性來設定適用於 MySQL 的 Azure 資料庫憑證。
logging.level.org.springframework.jdbc.core=DEBUG spring.datasource.url=jdbc:mysql://mysqlflexibletest.mysql.database.azure.com:3306/demo?serverTimezone=UTC spring.datasource.username=<your_mysql_ad_non_admin_username> spring.datasource.azure.passwordless-enabled=true spring.sql.init.mode=always警告
組態屬性
spring.sql.init.mode=always表示 Spring Boot 會在每次啟動伺服器時,使用 您下次建立的schema.sql 檔案,自動產生資料庫架構。 這項功能非常適合用於測試,但請記住,它會在每次重新啟動時刪除您的數據,因此您不應該在生產環境中使用它。設定屬性
spring.datasource.url附加了?serverTimezone=UTC,以指示 JDBC 驅動程式在連線到資料庫時,使用 UTC 日期格式 (或國際標準時間)。 如果沒有這個參數,你的 Java 伺服器就不會使用與資料庫相同的日期格式,這會導致錯誤。
- 如果沒有,請建立一個名為
mysqlsingletest的 適用於 MySQL 的 Azure 資料庫 單一伺服器實例。 相關說明請參見 快速入門:使用 Azure portal 建立適用於 MySQL 的 Azure 資料庫伺服器。 然後,建立名為demo的資料庫。 有關說明,請參閱 在 適用於 MySQL 的 Azure 資料庫 建立使用者的 建立資料庫節。
請參閱範例應用程式
在本文中,您將撰寫範例應用程式的程序代碼。 如果你想更快,這個應用程式已經編碼好,且在 https://github.com/Azure-Samples/quickstart-spring-data-jdbc-mysql 上有提供。
設定 MySQL 伺服器的防火牆規則
適用於 MySQL 的 Azure 資料庫 實例預設是安全的。 其防火牆不允許任何連入連線。
若要能夠使用您的資料庫,請開啟伺服器的防火牆,以允許本機 IP 位址存取資料庫伺服器。 欲了解更多資訊,請參閱 透過 Azure portal 建立及適用於 MySQL 的 Azure 資料庫管理防火牆規則。
如果你是從 Windows 電腦上的 Windows 子系統 Linux 版(WSL)連接到 MySQL 伺服器,你需要在防火牆上加入 WSL 主機 IP 位址。
建立 MySQL 非系統管理員使用者並授與權限
此步驟會建立非系統管理員使用者,並將資料庫的所有許可權 demo 授與其。
重要
要使用無密碼連線,請為你的 適用於 MySQL 的 Azure 資料庫 實例建立一個 Microsoft Entra 管理員使用者。 欲了解更多資訊,請參閱 Use Microsoft Entra ID for authentication with MySQL 中 Setting the Microsoft Entra Admin user 部分。
建立名為 create_ad_user.sql 的 SQL 腳本,以建立非系統管理員使用者。 新增下列內容,並將其儲存在本地:
export AZ_MYSQL_AD_NON_ADMIN_USERID=$(az ad signed-in-user show --query id --output tsv)
cat << EOF > create_ad_user.sql
SET aad_auth_validate_oids_in_tenant = OFF;
CREATE AADUSER '<your_mysql_ad_non_admin_username>' IDENTIFIED BY '$AZ_MYSQL_AD_NON_ADMIN_USERID';
GRANT ALL PRIVILEGES ON demo.* TO '<your_mysql_ad_non_admin_username>'@'%';
FLUSH privileges;
EOF
接著,使用以下指令執行 SQL 腳本,建立 Microsoft Entra 非管理員使用者:
mysql -h mysqlsingletest.mysql.database.azure.com --user <your_mysql_ad_admin_username>@mysqlsingletest --enable-cleartext-plugin --password=$(az account get-access-token --resource-type oss-rdbms --output tsv --query accessToken) < create_ad_user.sql
提示
要使用 Microsoft Entra 認證連接 適用於 MySQL 的 Azure 資料庫,你需要用你設定的 Microsoft Entra 管理員登入,然後取得存取權杖作為密碼。 欲了解更多資訊,請參閱 使用 Microsoft Entra ID 進行 MySQL 認證。
儲存來自 Azure MySQL 資料庫的資料
現在你已經有一個 適用於 MySQL 的 Azure 資料庫 單伺服器實例,可以用 Spring Cloud Azure 來儲存資料。
要安裝 Spring Cloud Azure Starter JDBC MySQL 模組,請在您的 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-dependencies為7.2.0.如果你用的是 Spring Boot 3.5.x,記得把版本設
spring-cloud-azure-dependencies成6.2.0。如果你使用的是 Spring Boot 3.1.x-3.5.x,記得把版本設
spring-cloud-azure-dependencies為5.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 MySQL 構件:
<dependency> <groupId>com.azure.spring</groupId> <artifactId>spring-cloud-azure-starter-jdbc-mysql</artifactId> </dependency>
注意
自 版本 4.5.0以來,已支援無密碼連線。
設定 Spring Boot 使用 Azure MySQL 資料庫
若要使用 Spring Data JDBC 從 適用於 MySQL 的 Azure 資料庫 儲存資料,請依照以下步驟設定應用程式:
請透過在你的 application.properties 設定檔中新增以下屬性來設定適用於 MySQL 的 Azure 資料庫憑證。
logging.level.org.springframework.jdbc.core=DEBUG spring.datasource.url=jdbc:mysql://mysqlsingletest.mysql.database.azure.com:3306/demo?serverTimezone=UTC spring.datasource.username=<your_mysql_ad_non_admin_username>@mysqlsingletest spring.datasource.azure.passwordless-enabled=true spring.sql.init.mode=always警告
組態屬性
spring.sql.init.mode=always表示 Spring Boot 會在每次啟動伺服器時,使用 您下次建立的schema.sql 檔案,自動產生資料庫架構。 這項功能非常適合用於測試,但請記住,它會在每次重新啟動時刪除您的數據,因此您不應該在生產環境中使用它。設定屬性
spring.datasource.url附加了?serverTimezone=UTC,以指示 JDBC 驅動程式在連線到資料庫時,使用 UTC 日期格式 (或國際標準時間)。 如果沒有這個參數,你的 Java 伺服器就不會使用與資料庫相同的日期格式,這會導致錯誤。
建立 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);
建立一個新的
TodoJava 類別。 這個類別是一個映射到todo數據表的領域模型,該數據表將由 Spring Boot 自動建立。 下列程式碼忽略了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; }編輯啟動類別檔案以顯示下列內容。
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資源的受管理身份是什麼?
啟動應用程式。 應用程式會將資料儲存至資料庫。 您會看到類似下列範例的記錄:
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 應用程式。