Using MySQL

Using MySQL

If the H2 JDBC driver is present in the application classpath, Spring Boot automatically configures an in-memory H2 database. Although H2 is very useful for prototyping and testing, it is not suitable for mission-critical, high-throughput, or enterprise-scale systems.

Let’s describe how to replace H2 with MySQL.

First, we need to ensure that the MySQL JDBC driver is a runtime dependency of the application. Incidentally, we will change the dependency on H2 to testRuntimeOnly.

1testRuntimeOnly("com.h2database:h2")
2runtimeOnly("com.mysql:mysql-connector-j")

To install MySQL on your computer, refer to the official documentation.

Let’s create the database and a dedicated user with appropriate privileges (the command lines below were executed on Ubuntu).

$ sudo mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.43-0ubuntu0.24.04.2 (Ubuntu)

Copyright (c) 2000, 2025, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database springbootdemodb;
Query OK, 1 row affected (0.01 sec)

mysql> CREATE USER 'springbootdemouser'@'localhost' IDENTIFIED BY 'secret';
Query OK, 0 rows affected (0.03 sec)

mysql> GRANT CREATE, ALTER, DROP, INSERT, UPDATE, DELETE, SELECT on springbootdemodb.* TO 'springbootdemouser'@'localhost' WITH GRANT OPTION;
Query OK, 0 rows affected (0.01 sec)

mysql> exit
Bye

Let’s check that springbootdemouser can connect.

$ mysql -u springbootdemouser -p springbootdemodb
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.43-0ubuntu0.24.04.2 (Ubuntu)

Copyright (c) 2000, 2025, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> exit
Bye

In the application.yml (or application.properties) file, let’s configure the connection to MySQL.

Note
The spring.jpa.hibernate.ddl-auto property is set to none. We do not want to generate the database when the application starts. We prefer to use migration tools such as Flyway or Liquibase.
 1spring:
 2  application:
 3   name: spring-boot-demo
 4  datasource:
 5    url: jdbc:mysql://localhost/springbootdemodb
 6    driverClassName: com.mysql.cj.jdbc.Driver
 7    username: springbootdemouser
 8    password: secret
 9  jpa:
10    hibernate:
11      ddl-auto: none