Spring Boot Database Connection

Spring Boot connects to a database using a DataSource. The DataSource manages a pool of database connections that your app reuses. You configure it in application.properties and Spring Boot sets everything up.

Connection Pool Analogy

Without a pool:                    With a connection pool:
─────────────────────────────      ─────────────────────────────────────────
Request 1: open connection         Pool starts with 10 ready connections
  → do work                        
  → close connection               Request 1: borrow connection #1
                                   Request 2: borrow connection #2
Request 2: open connection         ...
  → do work                        Request 1 done: return connection #1
  → close connection               Request 11: borrow connection #1 again

Opening/closing is slow.           Borrowing/returning is instant.

Spring Boot uses HikariCP as the default connection pool — one of the fastest available.

Connecting to MySQL

Add the MySQL dependency to pom.xml

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
</dependency>

Configure in application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/estudy_db?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=secret
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect

Connecting to PostgreSQL

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
</dependency>
spring.datasource.url=jdbc:postgresql://localhost:5432/estudy_db
spring.datasource.username=postgres
spring.datasource.password=secret
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect

Using H2 In-Memory Database for Development

H2 is a lightweight in-memory database built into Spring Boot. Data disappears when the app restarts — ideal for testing and local development.

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.h2.console.enabled=true   ← Access browser UI at /h2-console

HikariCP Connection Pool Settings

# Maximum connections in the pool
spring.datasource.hikari.maximum-pool-size=10

# Minimum idle connections kept ready
spring.datasource.hikari.minimum-idle=5

# How long to wait for a connection (ms)
spring.datasource.hikari.connection-timeout=30000

# How long a connection can stay idle (ms)
spring.datasource.hikari.idle-timeout=600000

# Max lifetime of a connection (ms) — prevent stale connections
spring.datasource.hikari.max-lifetime=1800000

Connection URL Structure

jdbc:mysql://localhost:3306/estudy_db?useSSL=false
  │     │         │          │              │
  │     │         │          │              └── Extra options
  │     │         │          └── Database name
  │     │         └── Host and port
  │     └── Database type
  └── JDBC protocol

jdbc:postgresql://db.myserver.com:5432/production_db
jdbc:h2:mem:testdb
jdbc:sqlserver://server;databaseName=mydb

Database Connection Flow

  App starts
      │
      ▼
  HikariCP creates 10 connections to MySQL
  and keeps them in the pool
      │
      ▼
  HTTP Request arrives
      │
      ▼
  Repository method called
      │
      ▼
  Borrow a connection from HikariCP pool
      │
      ▼
  Execute SQL query
      │
      ▼
  Return connection to pool
      │
      ▼
  Response sent to client

Testing the Connection

Add this to verify the datasource on startup:

@Component
public class DatabaseChecker {

    @Autowired
    private DataSource dataSource;

    @PostConstruct
    public void check() throws Exception {
        System.out.println("DB connected: " +
            dataSource.getConnection().getMetaData().getURL());
    }
}

Summary

  • Spring Boot uses HikariCP for connection pooling by default
  • Configure the database URL, username, and password in application.properties
  • H2 is a fast in-memory database perfect for local development and testing
  • Tune HikariCP pool settings for your application's concurrency needs
  • Keep passwords in environment variables — never hardcode them in config files

Leave a Comment

Your email address will not be published. Required fields are marked *