Use Spring Data JDBC with Azure Database for MySQL
This topic demonstrates creating a sample application that uses Spring Data JDBC to store and retrieve information in Azure Database for MySQL.
JDBC is the standard Java API to connect to traditional relational databases.
In this article, we'll include two authentication methods: Azure Active Directory (Azure AD) authentication and MySQL authentication. The Passwordless tab shows the Azure AD authentication and the Password tab shows the MySQL authentication.
Azure AD authentication is a mechanism for connecting to Azure Database for MySQL using identities defined in Azure AD. With Azure AD authentication, you can manage database user identities and other Microsoft services in a central location, which simplifies permission management.
MySQL authentication uses accounts stored in MySQL. If you choose to use passwords as credentials for the accounts, these credentials will be stored in the user table. Because these passwords are stored in MySQL, you'll need to manage the rotation of the passwords by yourself.
Prerequisites
- An Azure account. If you don't have one, get a free trial.
- Azure Cloud Shell or Azure CLI 2.37.0 or above required. We recommend Azure Cloud Shell so you'll be logged in automatically and have access to all the tools you'll need.
- If you're using a Windows machine and want to run the samples locally, install and use the latest Windows Subsystem for Linux (WSL).
- MySQL command line client. You can connect to your server using a popular client tool, mysql.exe command-line tool with Azure Cloud Shell. Alternatively, you can use mysql command line on your local environment.
- A supported Java Development Kit, version 8 or above. (17 or above preferred. A JDK is included in Azure Cloud Shell). We recommend installing the Microsoft Build of OpenJDK.
- Apache's Maven, version 3 or later.
- A Git client.
- cURL or a similar HTTP utility to test functionality.
Sample application
In this article, we will code a sample application. If you want to go faster, this application is already coded and available at https://github.com/Azure-Samples/quickstart-spring-data-jdbc-mysql.
Prepare the working environment
First, set up some environment variables. In Azure Cloud Shell, run the following commands:
export AZ_RESOURCE_GROUP=database-workshop
export AZ_DATABASE_NAME=<YOUR_DATABASE_NAME>
export AZ_LOCATION=<YOUR_AZURE_REGION>
export AZ_MYSQL_AD_NON_ADMIN_USERNAME=spring-non-admin
export AZ_LOCAL_IP_ADDRESS=<YOUR_LOCAL_IP_ADDRESS>
export CURRENT_USERNAME=$(az ad signed-in-user show --query userPrincipalName -o tsv)
export CURRENT_USER_OBJECTID=$(az ad signed-in-user show --query id -o tsv)
Replace the placeholders with the following values, which are used throughout this article:
<YOUR_DATABASE_NAME>: The name of your MySQL server. It should be unique across Azure.<YOUR_AZURE_REGION>: The Azure region you'll use. You can useeastusby default, but we recommend that you configure a region closer to where you live. You can have the full list of available regions by enteringaz account list-locations.<YOUR_LOCAL_IP_ADDRESS>: The IP address of your local computer, from which you'll run your Spring Boot application. One convenient way to find it is to point your browser to whatismyip.akamai.com.
Next, create a resource group:
az group create \
--name $AZ_RESOURCE_GROUP \
--location $AZ_LOCATION \
--output tsv
Create an Azure Database for MySQL instance
Create a MySQL server and set up admin user
The first thing we'll create is a managed MySQL server with an admin user.
Note
You can read more detailed information about creating MySQL servers in Create an Azure Database for MySQL server by using the Azure portal.
If you're using Azure CLI, run the following command to make sure it has sufficient permission:
az login --scope https://graph.microsoft.com/.default
Run the following command to create the server:
az mysql server create \
--resource-group $AZ_RESOURCE_GROUP \
--name $AZ_DATABASE_NAME \
--location $AZ_LOCATION \
--sku-name B_Gen5_1 \
--storage-size 5120 \
--output tsv
Run the following command to set the Azure AD admin user:
az mysql server ad-admin create \
--resource-group $AZ_RESOURCE_GROUP \
--server-name $AZ_DATABASE_NAME \
--display-name $CURRENT_USERNAME \
--object-id $CURRENT_USER_OBJECTID
Important
When setting the administrator, a new user is added to the Azure Database for MySQL server with full administrator permissions. Only one Azure AD admin can be created per MySQL server and selection of another one will overwrite the existing Azure AD admin configured for the server.
This command creates a small MySQL server and sets the Active Directory admin to the signed-in user.
Configure a MySQL database
The MySQL server that you created earlier is empty. It doesn't have any database that you can use with the Spring Boot application. Create a new database called demo by using the following command:
az mysql db create \
--resource-group $AZ_RESOURCE_GROUP \
--name demo \
--server-name $AZ_DATABASE_NAME \
--output tsv
Configure a firewall rule for your MySQL server
Azure Database for MySQL instances are secured by default. They have a firewall that doesn't allow any incoming connection. To be able to use your database, you need to add a firewall rule that will allow the local IP address to access the database server.
Because you configured your local IP address at the beginning of this article, you can open the server's firewall by running the following command:
az mysql server firewall-rule create \
--resource-group $AZ_RESOURCE_GROUP \
--name $AZ_DATABASE_NAME-database-allow-local-ip \
--server $AZ_DATABASE_NAME \
--start-ip-address $AZ_LOCAL_IP_ADDRESS \
--end-ip-address $AZ_LOCAL_IP_ADDRESS \
--output tsv
If you're connecting to your MySQL server from WSL on a Windows computer, you'll need to add the WSL host ID to your firewall.
Obtain the IP address of your host machine by running the following command in WSL:
cat /etc/resolv.conf
Copy the IP address following the term nameserver, then use the following command to set an environment variable for the WSL IP Address:
AZ_WSL_IP_ADDRESS=<the-copied-IP-address>
Then, use the following command to open the server's firewall to your WSL-based app:
az mysql server firewall-rule create \
--resource-group $AZ_RESOURCE_GROUP \
--name $AZ_DATABASE_NAME-database-allow-local-ip-wsl \
--server $AZ_DATABASE_NAME \
--start-ip-address $AZ_WSL_IP_ADDRESS \
--end-ip-address $AZ_WSL_IP_ADDRESS \
--output tsv
Create a MySQL non-admin user and grant permission
This step will create a non-admin user and grant all permissions on the demo database to it.
Note
You can read more detailed information about creating MySQL users in Create users in Azure Database for MySQL.
We've already enabled the Azure AD authentication. This step will create an Azure AD user and grant permissions.
First, create a SQL script called create_ad_user.sql for creating a non-admin user. Add the following contents and save it locally:
AZ_MYSQL_AD_NON_ADMIN_USERID=$CURRENT_USER_OBJECTID
cat << EOF > create_ad_user.sql
SET aad_auth_validate_oids_in_tenant = OFF;
CREATE AADUSER '$AZ_MYSQL_AD_NON_ADMIN_USERNAME' IDENTIFIED BY '$AZ_MYSQL_AD_NON_ADMIN_USERID';
GRANT ALL PRIVILEGES ON demo.* TO '$AZ_MYSQL_AD_NON_ADMIN_USERNAME'@'%';
FLUSH privileges;
EOF
Then, use the following command to run the SQL script to create the Azure AD non-admin user:
mysql -h $AZ_DATABASE_NAME.mysql.database.azure.com --user $CURRENT_USERNAME@$AZ_DATABASE_NAME --enable-cleartext-plugin --password=$(az account get-access-token --resource-type oss-rdbms --output tsv --query accessToken) < create_ad_user.sql
Now use the following command to remove the temporary SQL script file:
rm create_ad_user.sql
Generate the application by using Spring Initializr
Generate the application on the command line by entering:
curl https://start.spring.io/starter.tgz -d dependencies=web,data-jdbc,mysql,azure-support -d baseDir=azure-database-workshop -d bootVersion=2.7.3 -d javaVersion=1.8 | tar -xzvf -
Note
Spring Cloud Azure currently supports passwordless connections only in version 4.5.0-beta.1. If you want to use passwordless connections, be sure to specify the version as 4.5.0-beta.1.
Configure Spring Boot to use Azure Database for MySQL
Open the src/main/resources/application.properties file, and add:
logging.level.org.springframework.jdbc.core=DEBUG
spring.datasource.url=jdbc:mysql://${AZ_DATABASE_NAME}.mysql.database.azure.com:3306/demo?serverTimezone=UTC
spring.datasource.username=${AZ_MYSQL_AD_NON_ADMIN_USERNAME}@${AZ_DATABASE_NAME}
spring.datasource.azure.passwordless-enabled=true
spring.sql.init.mode=always
Warning
The configuration property spring.sql.init.mode=always means that Spring Boot will automatically generate a database schema, using the schema.sql file that you'll create later, each time the server is started. This feature is great for testing, but remember that it will delete your data at each restart, so you shouldn't use it in production.
The configuration property spring.datasource.url has ?serverTimezone=UTC appended to tell the JDBC driver to use the UTC date format (or Coordinated Universal Time) when connecting to the database. Otherwise, your Java server would not use the same date format as the database, which would result in an error.
Note
This article describes the basic usage, but you can also use a service principal or managed identity to connect. For more information, see Connect to Azure MySQL using a service principal or Connect to Azure MySQL with Managed Identity in Azure Spring Apps.
You should now be able to start your application by using the provided Maven wrapper:
./mvnw spring-boot:run
Here's a screenshot of the application running for the first time:
Create the database schema
Spring Boot will automatically execute src/main/resources/schema.sql in order to create a database schema. Create that file, with the following content:
DROP TABLE IF EXISTS todo;
CREATE TABLE todo (id SERIAL PRIMARY KEY, description VARCHAR(255), details VARCHAR(4096), done BOOLEAN);
Stop the running application, and start it again. The application will now use the demo database that you created earlier, and create a todo table inside it.
./mvnw spring-boot:run
Code the application
Next, add the Java code that will use JDBC to store and retrieve data from your MySQL server.
Create a new Todo Java class, next to the DemoApplication class, and add the following code:
package com.example.demo;
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;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
}
This class is a domain model mapped on the todo table that you created before.
To manage that class, you'll need a repository. Define a new TodoRepository interface in the same package:
package com.example.demo;
import org.springframework.data.repository.CrudRepository;
public interface TodoRepository extends CrudRepository<Todo, Long> {
}
This repository is a repository that Spring Data JDBC manages.
Finish the application by creating a controller that can store and retrieve data. Implement a TodoController class in the same package, and add the following code:
package com.example.demo;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/")
public class TodoController {
private final TodoRepository todoRepository;
public TodoController(TodoRepository todoRepository) {
this.todoRepository = todoRepository;
}
@PostMapping("/")
@ResponseStatus(HttpStatus.CREATED)
public Todo createTodo(@RequestBody Todo todo) {
return todoRepository.save(todo);
}
@GetMapping("/")
public Iterable<Todo> getTodos() {
return todoRepository.findAll();
}
}
Finally, halt the application and start it again using the following command:
./mvnw spring-boot:run
Test the application
To test the application, you can use cURL.
First, create a new "todo" item in the database using the following command:
curl --header "Content-Type: application/json" \
--request POST \
--data '{"description":"configuration","details":"congratulations, you have set up JDBC correctly!","done": "true"}' \
http://127.0.0.1:8080
This command should return the created item as follows:
{"id":1,"description":"configuration","details":"congratulations, you have set up JDBC correctly!","done":true}
Next, retrieve the data by using a new cURL request as follows:
curl http://127.0.0.1:8080
This command will return the list of "todo" items, including the item you've created, as follows:
[{"id":1,"description":"configuration","details":"congratulations, you have set up JDBC correctly!","done":true}]
Here's a screenshot of these cURL requests:
Congratulations! You've created a Spring Boot application that uses JDBC to store and retrieve data from Azure Database for MySQL.
Clean up resources
To clean up all resources used during this quickstart, delete the resource group using the following command:
az group delete \
--name $AZ_RESOURCE_GROUP \
--yes
Next steps
To learn more about deploying a Spring Data application to Azure Spring Apps and using managed identity, see Tutorial: Deploy a Spring application to Azure Spring Apps with a passwordless connection to an Azure database.
To learn more about Spring and Azure, continue to the Spring on Azure documentation center.
Additional resources
For more information about Spring Data JDBC, see Spring's reference documentation.
For more information about using Azure with Java, see Azure for Java developers and Working with Azure DevOps and Java.
Feedback
Submit and view feedback for