Skip to lesson

Connecting Spring Boot to MySQL

ShopLite must read products and orders from a real MySQL database, not from fake data. The app has to connect safely, survive a wrong password with a clear message, and start with the right tables in place.

Recap: spring-boot-starter-jdbc and mysql-connector-j

A DataSource is the object that hands out database connections. Spring Boot builds it from the spring.datasource settings once the JDBC starter and the MySQL driver are on the classpath.

Two dependencies, both without a version, give Spring Boot everything it needs to reach MySQL. The Boot parent picks versions that are tested together.

Example 1 · pom.xml: the JDBC starter and the MySQL driver

Runs in: the shoplite-api Spring Boot project with the ShopLite MySQL database

XML
<!-- pom.xml (inside <dependencies>): no <version> tags, the Boot parent picks them --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency>    <groupId>com.mysql</groupId>    <artifactId>mysql-connector-j</artifactId>    <scope>runtime</scope></dependency>
Sample output
$ mvn dependency:tree -Dincludes=com.mysql,com.zaxxer,org.springframework:spring-jdbc
[INFO] com.shoplite:shoplite-api:jar:1.0.0
[INFO] +- org.springframework.boot:spring-boot-starter-jdbc:jar:4.1.1:compile
[INFO] |  +- org.springframework.boot:spring-boot-jdbc:jar:4.1.1:compile
[INFO] |  |  \- org.springframework:spring-jdbc:jar:7.0.9:compile
[INFO] |  \- com.zaxxer:HikariCP:jar:7.0.2:compile
[INFO] \- com.mysql:mysql-connector-j:jar:9.7.0:runtime

What this code does

  • The starter pulls in spring-jdbc (JdbcClient, JdbcTemplate, transactions) and HikariCP 7.0.2: one dependency, the whole JDBC toolbox.
  • The driver arrives as version 9.7.0 with scope runtime, chosen by Spring Boot 4.1.1, not by you.

spring-boot-starter-jdbc brings Spring's JDBC module (JdbcClient, JdbcTemplate, transactions) and HikariCP, the connection pool. mysql-connector-j is MySQL's JDBC driver, the library that speaks MySQL's network protocol.

The driver has <scope>runtime</scope>: your code never imports a MySQL class, so the compiler cannot see it and nobody depends on it by accident. In Section 13 you built the HikariDataSource yourself and pinned every version; now the Boot parent manages both.

Do not copy the Section 13 versions (mysql-connector-j 26.7.0, HikariCP 7.1.0) into this pom. Spring Boot 4.1.1 picks its own tested versions, and a <version> tag would override them.

Recap: spring.datasource from environment variables

An environment variable is a named value that the terminal or server gives to a program. Spring reads it with ${NAME}, so the password lives on the machine, not in Git.

Boot needs three settings to build the DataSource: the URL, the user name and the password. ShopLite writes each one as a placeholder for an environment variable.

Text
# The database. The values come from environment variables, never from this file.spring.datasource.url=${DB_URL}spring.datasource.username=${DB_USER}spring.datasource.password=${DB_PASSWORD}

Example 2 · Run with the password from an environment variable

Runs in: the shoplite-api Spring Boot project with the ShopLite MySQL database

Terminal
# Windows PowerShell (macOS: export DB_PASSWORD="your-mysql-password")$env:DB_PASSWORD = "your-mysql-password"java -jar target/shoplite-api-1.0.0.jar
Sample output
INFO  com.shoplite.ShopliteApiApplication : Starting ShopliteApiApplication v1.0.0 using Java 21.0.7 with PID 1892 (...)
INFO  com.shoplite.ShopliteApiApplication : No active profile set, falling back to 1 default profile: "dev"
INFO  o.s.boot.tomcat.TomcatWebServer : Tomcat started on port 8080 (http) with context path '/'
INFO  com.shoplite.ShopliteApiApplication : Started ShopliteApiApplication in 18.467 seconds (process running for 19.894)
INFO  com.zaxxer.hikari.HikariDataSource : ShopLitePool - Starting...
INFO  com.zaxxer.hikari.pool.HikariPool : ShopLitePool - Added connection com.mysql.cj.jdbc.ConnectionImpl@175bf9c9
INFO  com.zaxxer.hikari.HikariDataSource : ShopLitePool - Start completed.
INFO  c.shoplite.common.DatabaseStartupCheck : Connected to MySQL 9.4.0, database shoplite

What this code does

  • No profile is set, so dev is used: DB_URL and DB_USER fall back to localhost:3306/shoplite and root, and only the password comes from the environment.
  • Tomcat starts first. Then the startup check asks for a connection, so ShopLitePool - Starting... and Added connection appear, and the last line confirms which server and database answered.
  • Timestamps and process ids are trimmed from these log lines; your MySQL version may differ (8.4 LTS is recommended).

You wrote these placeholders in the Configuration module, with a default URL and user in the dev profile. The lines do not change; what is new is that the app uses them on every request, so a wrong value matters at once.

The JDBC URL has a fixed shape: jdbc:mysql:// + host + : + port + / + database name. Port 3306 is MySQL's default, and a typo in any part gives one of the startup errors later in this lesson.

Never write spring.datasource.password=mypassword in a committed file. Anyone who can read the repository, today or in five years, can then log in to your database.

HikariCP: the pool Boot sets up for you

A connection pool keeps a few open database connections and lends them to requests, so no request has to log in to MySQL itself. Spring Boot uses HikariCP for this.

With spring-boot-starter-jdbc on the classpath, Boot creates a HikariCP pool and fills it from the spring.datasource.* settings. You tune it with spring.datasource.hikari.*.

Three ShopLite requests borrow connections from a HikariCP pool of four open connections to MySQL. Two are in use, two idle. A third request waits for a free connection and fails after connection-timeout.

Example 3 · See the pool settings Hikari really uses

Runs in: the shoplite-api Spring Boot project with the ShopLite MySQL database

Terminal
java -jar target/shoplite-api-1.0.0.jar --spring.datasource.hikari.maximum-pool-size=5 --spring.datasource.hikari.connection-timeout=3000 --logging.level.com.zaxxer.hikari.HikariConfig=DEBUG
Sample output (selected lines)
DEBUG com.zaxxer.hikari.HikariConfig : ShopLitePool - configuration:
DEBUG com.zaxxer.hikari.HikariConfig : connectionTimeout...............3000
DEBUG com.zaxxer.hikari.HikariConfig : idleTimeout.....................600000
DEBUG com.zaxxer.hikari.HikariConfig : keepaliveTime...................120000
DEBUG com.zaxxer.hikari.HikariConfig : maxLifetime.....................1800000
DEBUG com.zaxxer.hikari.HikariConfig : maximumPoolSize.................5
DEBUG com.zaxxer.hikari.HikariConfig : minimumIdle.....................5
DEBUG com.zaxxer.hikari.HikariConfig : poolName........................"ShopLitePool"
INFO  com.zaxxer.hikari.HikariDataSource : ShopLitePool - Starting...
INFO  com.zaxxer.hikari.HikariDataSource : ShopLitePool - Start completed.

What this code does

  • Command-line arguments override application.properties, so this run uses a pool of 5 with a 3-second timeout. The DEBUG log of HikariConfig prints every setting the pool ended up with.
  • minimumIdle follows maximumPoolSize (5), and the other values are Hikari's defaults: idle connections closed after 10 minutes, every connection replaced after 30.

Opening a MySQL connection takes tens of milliseconds; borrowing one from the pool takes microseconds. The settings you will meet:

  • maximum-pool-size: most open connections (default 10).
  • minimum-idle: connections kept ready; by default the same as the maximum.
  • connection-timeout: milliseconds a caller waits for a free connection (default 30000; ShopLite uses 5000).
  • max-lifetime: a connection is replaced after this time (default 1800000, 30 minutes).

The pool is lazy: it opens a connection only when the first query asks, which is why ShopLite runs one small query at startup. Bigger is not better: MySQL serves each connection with its own thread, so 10 to 20 connections per app instance is normal.

Predict the output

Predict the pool

Read the settings, then pick what happens.

Round 1 of 2

Three requests arrive together and each keeps its connection for 10 seconds. What happens to the third?

spring.datasource.hikari.maximum-pool-size=2
spring.datasource.hikari.connection-timeout=5000

Startup errors: Communications link failure and Access denied

A startup check is a small piece of code that uses the database once while the app starts, so a wrong setting stops the app at once instead of failing a customer's request.

ShopLite's DatabaseStartupCheck runs SELECT VERSION(), DATABASE() and logs the answer. When the connection fails, the log has many lines: read the last Caused by: line first.

Example 4 · src/main/java/com/shoplite/common/DatabaseStartupCheck.java

Runs in: the shoplite-api Spring Boot project with the ShopLite MySQL database

Java
package com.shoplite.common;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.boot.ApplicationArguments;import org.springframework.boot.ApplicationRunner;import org.springframework.jdbc.core.simple.JdbcClient;import org.springframework.stereotype.Component;
/** * Talks to MySQL once at startup. The pool connects lazily, so without this a wrong URL or password * would show up only at the first request; now the app stops at startup with the real error. */@Componentclass DatabaseStartupCheck implements ApplicationRunner {
    private static final Logger log = LoggerFactory.getLogger(DatabaseStartupCheck.class);
    private final JdbcClient jdbc;
    DatabaseStartupCheck(JdbcClient jdbc) {        this.jdbc = jdbc;    }
    @Override    public void run(ApplicationArguments args) {        String info = jdbc.sql("SELECT CONCAT('MySQL ', VERSION(), ', database ', DATABASE())")                .query(String.class)                .single();        log.info("Connected to {}", info);    }}
Sample output (stack trace lines trimmed)
$ java -jar target/shoplite-api-1.0.0.jar      (DB_URL with port 3399 by mistake)
INFO  com.shoplite.ShopliteApiApplication : Started ShopliteApiApplication in 11.656 seconds (process running for 12.877)
INFO  com.zaxxer.hikari.HikariDataSource : ShopLitePool - Starting...
ERROR o.s.boot.SpringApplication : Application run failed
org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection
Caused by: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Caused by: java.net.ConnectException: Connection refused: getsockopt

What this code does

  • An ApplicationRunner runs once after the app has started. Its query makes Hikari open the first connection, so a bad setting fails here, at startup, and Boot stops the app.
  • Read from the bottom: Connection refused means nothing listens on port 3399. MySQL was running on 3306, so fixing DB_URL fixes the error.

Example 5 · Three more startup errors and what they mean

Runs in: the shoplite-api Spring Boot project with the ShopLite MySQL database

Text
1) DB_PASSWORD wrong2) DB_URL ends in /shoplitee (typo)3) prod profile, DB_URL not set at all
Sample output (the last line of each error)
1) Caused by: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

2) Caused by: java.sql.SQLSyntaxErrorException: Unknown database 'shoplitee'

3) Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception with message: 'url' must start with "jdbc"

What this code does

  • Access denied: MySQL answered, so host and port are right; check DB_USER and DB_PASSWORD. "using password: YES" tells you a password was sent, just not the right one.
  • Unknown database: the login worked; create the database with the schema script or fix the name in DB_URL. The url message means the variable was missing and ${DB_URL} stayed as literal text.

The last Caused by: line names the real problem:

  • Communications link failure with Connection refused: nothing answered at that host and port. MySQL is not running, or the port in DB_URL is wrong.
  • Access denied for user: MySQL answered but rejected the user name or password.
  • Unknown database 'shoplitee': the server and login are fine, but the name after the last / does not exist.
  • 'url' must start with "jdbc": DB_URL was not set, so the placeholder ${DB_URL} stayed as plain text.

Fix the error

Fix the connection setting

Each round shows the startup error. Pick the line that fixes it.

Round 1 of 3

MySQL listens on port 3306. Which line replaces line 1?

DB_URL=jdbc:mysql://localhost:3307/shoplite
DB_USER=shop_app
DB_PASSWORD=********

Error

Communications link failure
Caused by: java.net.ConnectException: Connection refused

Loading the ShopLite schema once with a script

A schema is the set of tables, keys and checks of a database. ShopLite's schema from Section 12 is saved in the repository as db/shoplite-schema.sql.

One command loads the schema with the mysql client. It creates the shoplite database, the six tables and the seed rows, then prints a row count per table.

Terminal
mysql -u root -p < db/shoplite-schema.sql
Output
customers	addresses	categories	products	orders	order_items
8	9	7	15	16	28

The app itself never creates or changes tables. A Spring Boot app can run SQL scripts at startup (spring.sql.init.mode=always), but this script starts with DROP TABLE, so running it on every start would wipe the shop each time.

Section 16 hands the schema to Flyway, a tool that applies numbered change scripts exactly once each.

Order of execution

First run, in order

Put the steps in the order you do them on a new computer.

The < sends the file into mysql; -p makes it ask for your password first. In PowerShell, < does not work: use Get-Content db/shoplite-schema.sql | mysql -u root -p or run source db/shoplite-schema.sql inside the mysql> prompt.

Next step

Check your understanding

12 quick questions