Connect Spring Boot to PostgreSQL: Driver, application.yml and the Hikari Pool
Connect the Relay support desk to PostgreSQL 18: one compose service, one driver line in the pom, a datasource in application.yml with a strict prod profile, and a small runner that asks the server who it is through the Hikari pool.
What you will learn
- Start PostgreSQL 18 with one Docker Compose service
- Add the PostgreSQL driver and write the datasource in application.yml
- Keep dev defaults friendly and the prod profile strict
- Explain what the Hikari connection pool does on every call
Before you start
- A first Spring Boot project
- Docker installed
- Basic SQL
Relay is the support desk we build in this part of the course. Every customer request becomes a ticket, and every ticket has to live somewhere safe. That place is PostgreSQL. The good news: connecting to it takes a driver, a URL and a login. The Java code on top stays the same.
In this article you start the server, add the driver, fill in application.yml, and watch the connection pool lend a connection for one query.
Where this sits in Relay
Relay is built in layers. Our own code asks for data. Below it, later, come repositories and entities. Today we only light up the bottom two layers: the data access layer (here JdbcTemplate and the Hikari pool) and PostgreSQL itself.
One compose service: PostgreSQL is running
You don't install PostgreSQL. You describe it in compose.yaml and let Docker run it. Here is the db service from the project:
name: relay
services:
db:
image: postgres:18
environment:
POSTGRES_DB: relay
POSTGRES_USER: relay
POSTGRES_PASSWORD: ${DB_PASSWORD:-relay}
ports:
- "${DB_PORT:-5432}:5432" # the door: psql or the app on your machine can knock here
volumes:
- relay-data:/var/lib/postgresql # the data survives a restart
healthcheck:
test: ["CMD-SHELL", "pg_isready -U relay -d relay"]
interval: 3s
timeout: 3s
retries: 20
volumes:
relay-data:
The three environment lines create the database, the user and the password on the very first start. The port line is the door. The volume keeps the rows after a restart. One command starts it:
docker compose up -d db
Network relay_default Created
Volume relay_relay-data Created
Container relay-db-1 Created
Container relay-db-1 Started
If you want to see that PostgreSQL really is there, docker compose exec db psql -U relay -d relay -c "\l" lists the databases, and relay is one of them. The file is plain text, so it travels with the project.
One new line in the pom: the driver
<!-- the PostgreSQL driver -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
The driver is the translator between Java and PostgreSQL, and it's the one line that changes when the database changes (in the blog project it was sqlite-jdbc). Its scope is runtime because your code never imports it directly. Above it, spring-boot-starter-jdbc brings JdbcTemplate and the HikariCP pool, so you add nothing else.
application.yml: URL, login and two profiles
spring:
application:
name: relay
datasource:
# dev, the default
url: jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/relay
username: relay
password: ${DB_PASSWORD:relay}
hikari:
maximum-pool-size: 10 # small on purpose
---
spring:
config:
activate:
on-profile: prod # nothing but the environment
datasource:
url: ${DB_URL}
username: ${DB_USER}
password: ${DB_PASSWORD}
Read ${DB_HOST:localhost} as "use the environment variable DB_HOST, and if it's missing, use localhost". The dev defaults match compose.yaml, so on your machine you set nothing. The prod profile has no defaults at all. Every value has to arrive from the environment, so no real secret ever sits in the file. Dev is friendly, prod is strict.
Ask the server who it is
ConnectionCheck is a CommandLineRunner, so Spring runs it once when the app starts. It asks three questions:
package org.studyeasy.relay;
import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class ConnectionCheck implements CommandLineRunner {
private final JdbcTemplate jdbc;
private final DataSource ds;
public ConnectionCheck(JdbcTemplate jdbc, DataSource ds) {
this.jdbc = jdbc;
this.ds = ds;
}
private String ask(String sql) {
return jdbc.queryForObject(sql, String.class);
}
@Override
public void run(String... args) {
String version = ask("select version()");
System.out.println("Server: " + version.split(" on ")[0]);
System.out.println("User: " + ask("select current_user"));
HikariDataSource pool = (HikariDataSource) ds;
System.out.println("Pool size: " + pool.getMaximumPoolSize());
}
}
Run RelayApplication (Spring Boot 4.1.2, Java 25, postgres:18). The Run window shows, with the log lines shortened:
HikariPool-1 - Starting...
HikariPool-1 - Added connection org.postgresql.jdbc.PgConnection@3a36cd5
HikariPool-1 - Start completed.
Server: PostgreSQL 18.6 (Debian 18.6-1.pgdg13+2)
User: relay
Pool size: 10
The last three lines are ours. The server names itself, the login worked, and the pool holds ten. The three Hikari lines aren't ours: Spring Boot built the pool from application.yml without a single line of Java.
One call, through the pool
What happens on jdbc.queryForObject("select version()", String.class)? The call waits while JdbcTemplate asks the pool for a connection. The pool lends one, so idle connections drop from ten to nine. The query goes down that connection, PostgreSQL answers with one row, and the String comes back to our code. The connection goes back to the pool, and idle is ten again.
Why keep the pool small? Check from the database side while Relay runs. Counting the connections to relay in pg_stat_activity (leaving psql's own out) gives 10, the whole pool. show max_connections gives 100, the server's limit, shared by every app that connects. Three copies of an app with a pool of 40 would ask for 120 and some would be refused.
Break it: one letter off in the password
Change the dev default to ${DB_PASSWORD:rely} and run again:
INFO HikariPool-1 - Starting...
ERROR Application run failed
org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection
Caused by: org.postgresql.util.PSQLException: FATAL: password authentication failed for user "relay"
The process ends with exit code 1. This is the error you'll meet most often with a new database, and the last line tells you exactly what's wrong. Put relay back and it starts again.
Common mistakes
- Putting real passwords in
application.yml. Keep defaults only for local dev, and give prod nothing but${...}placeholders. - Using
localhostinside Docker. When the app runs in a container too, the database host is the service name,db. That's why the URL reads${DB_HOST:localhost}. - A big pool "for speed". Each connection is a slot on a server limited to 100. Start at 10 and measure.
- Forgetting the volume. Without
relay-data, adocker compose downtakes your rows with it.
Recap
| Piece | Where | Job |
|---|---|---|
db service | compose.yaml | runs postgres:18 with a user, a database and a volume |
| Driver | pom.xml, scope runtime | talks PostgreSQL's protocol |
| Datasource | application.yml | URL and login, dev defaults, strict prod profile |
| Hikari pool | built by Spring Boot | keeps 10 connections open and lends them |
JdbcTemplate | your code | borrows a connection, runs SQL, gives it back |
Try it yourself
Set maximum-pool-size: 3 and run again. The last line should say Pool size: 3. Then count the connections in pg_stat_activity once more and see if the database agrees.
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
A one-line JpaRepository interface and a small @Service class save and read blog posts with no SQL. Follow one save and one read through every layer, then prove it with a test.
Entities and H2 in Spring Boot: a Post Class Becomes a Table
The blog's cards are typed into HTML. A Post class with @Entity and @Id becomes the POST table in an in-memory H2 database: three pom lines, a few YAML settings, and Hibernate writes the create table SQL at startup.
Seed Data and Posts on the Homepage: CommandLineRunner, the Model and th:each
SeedData, a CommandLineRunner, saves three posts when the POST table is empty. HomeController puts postService.getAll() into the Model, and one postCard inside th:each becomes three cards. Three inserts at startup, one select per visit.
Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
Eight posts, three to a page, newest first. HomeController turns ?page=1&sort=oldest into a PageRequest, PostService passes it to findAll(Pageable), H2 runs one select with an offset and one count, and the Page that comes back knows it is page 2 of 3.
