Use Spring Data JDBC with Azure SQL Database

This tutorial demonstrates how to store data in Azure SQL Database using Spring Data JDBC.

JDBC is the standard Java API to connect to traditional relational databases.

In this tutorial, we include two authentication methods: Microsoft Entra authentication and SQL Database authentication. The Passwordless tab shows the Microsoft Entra authentication and the Password tab shows the SQL Database authentication.

Microsoft Entra authentication is a mechanism for connecting to Azure Database for SQL Database using identities defined in Microsoft Entra ID. With Microsoft Entra authentication, you can manage database user identities and other Microsoft services in a central location, which simplifies permission management.

SQL Database authentication uses accounts stored in SQL Database. 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 SQL Database, you need to manage the rotation of the passwords by yourself.

Prerequisites

  • sqlcmd Utility.

  • ODBC Driver 17 or 18.

  • If you don't have one, create an Azure SQL Server instance named sqlservertest and a database named demo. For instructions, see Quickstart: Create a single database - Azure SQL Database.

  • If you don't have a Spring Boot application, create a Maven project with the Spring Initializr. Be sure to select Maven Project and, under Dependencies, add the Spring Web, Spring Data JDBC, and MS SQL Server Driver dependencies, and then select Java version 8 or higher.

See the sample application

In this tutorial, you'll 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-sql-server.

Configure a firewall rule for your Azure SQL Database server

Azure SQL Database instances are secured by default. They have a firewall that doesn't allow any incoming connection.

To be able to use your database, open the server's firewall to allow the local IP address to access the database server. For more information, see Tutorial: Secure a database in Azure SQL Database.

If you're connecting to your Azure SQL Database server from Windows Subsystem for Linux (WSL) on a Windows computer, you need to add the WSL host ID to your firewall.

Create an SQL database non-admin user and grant permission

This step will create a non-admin user and grant all permissions on the demo database to it.

To use passwordless connections, see Tutorial: Secure a database in Azure SQL Database or use Service Connector to create a Microsoft Entra admin user for your Azure SQL Database server, as shown in the following steps:

  1. First, install the Service Connector passwordless extension for the Azure CLI:

    az extension add --name serviceconnector-passwordless --upgrade
    
  2. Then, use the following command to create the Microsoft Entra non-admin user:

    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
    

The Microsoft Entra admin you created is an SQL database admin user, so you don't need to create a new user.

Important

Azure SQL database passwordless connections require upgrading the MS SQL Server Driver to version 12.1.0 or higher. The connection option is authentication=DefaultAzureCredential in version 12.1.0 and authentication=ActiveDirectoryDefault in version 12.2.0.

Store data from Azure SQL Database

With an Azure SQL Database instance, you can store data by using Spring Cloud Azure.

To install the Spring Cloud Azure Starter module, add the following dependencies to your pom.xml file:

  • The Spring Cloud Azure Bill of Materials (BOM):

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

    Note

    If you're using Spring Boot 2.x, be sure to set the spring-cloud-azure-dependencies version to 4.19.0. This Bill of Material (BOM) should be configured in the <dependencyManagement> section of your pom.xml file. This ensures that all Spring Cloud Azure dependencies are using the same version. For more information about the version used for this BOM, see Which Version of Spring Cloud Azure Should I Use.

  • The Spring Cloud Azure Starter artifact:

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

    Note

    As this is a dependency, it should be added in the <dependencies> section of the pom.xml. Its version is not configured here, as it is managed by the BOM that we added previously.

Configure Spring Boot to use Azure SQL Database

To store data from Azure SQL Database using Spring Data JDBC, follow these steps to configure the application:

  1. Configure an Azure SQL Database credentials in the application.properties configuration file.

    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
    

    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 next, each time the server is started. This is great for testing, but remember that this will delete your data at each restart, so you shouldn't use it in production.

  1. Create the src/main/resources/schema.sql configuration file to configure the database schema, then add the following contents.

    DROP TABLE IF EXISTS todo;
    CREATE TABLE todo (id INT IDENTITY PRIMARY KEY, description VARCHAR(255), details VARCHAR(4096), done BIT);
    
  1. Create a new Todo Java class. This class is a domain model mapped onto the todo table that will be created automatically by Spring Boot. The following code ignores the getters and setters methods.

    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. Edit the startup class file to show the following content.

    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> {
    
    }
    

    Tip

    In this tutorial, there are no authentication operations in the configurations or the code. However, connecting to Azure services requires authentication. To complete the authentication, you need to use Azure Identity. Spring Cloud Azure uses DefaultAzureCredential, which the Azure Identity library provides to help you get credentials without any code changes.

    DefaultAzureCredential supports multiple authentication methods and determines which method to use at runtime. This approach enables your app to use different authentication methods in different environments (such as local and production environments) without implementing environment-specific code. For more information, see DefaultAzureCredential.

    To complete the authentication in local development environments, you can use Azure CLI, Visual Studio Code, PowerShell, or other methods. For more information, see Azure authentication in Java development environments. To complete the authentication in Azure hosting environments, we recommend using user-assigned managed identity. For more information, see What are managed identities for Azure resources?

  3. Start the application. The application stores data into the database. You'll see logs similar to the following example:

    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
    

Deploy to Azure Spring Apps

Now that you have the Spring Boot application running locally, it's time to move it to production. Azure Spring Apps makes it easy to deploy Spring Boot applications to Azure without any code changes. The service manages the infrastructure of Spring applications so developers can focus on their code. Azure Spring Apps provides lifecycle management using comprehensive monitoring and diagnostics, configuration management, service discovery, CI/CD integration, blue-green deployments, and more. To deploy your application to Azure Spring Apps, see Deploy your first application to Azure Spring Apps.

Next steps