Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Spring Boot
  • Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
  • A Plain Spring Project, No Boot: Your First Bean With spring-context
  • Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
  • Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
  • Spring Autowiring: Spring Fills the Constructor, and When @Autowired Is Needed
  • Two Beans, One Type: Spring @Primary and @Qualifier
  • Spring Bean Scopes: Singleton vs Prototype, One Shared Object or a Fresh One
  • Spring Stereotypes: @Service, @Repository and @Controller Are @Component With a Job Name
  • The Spring Bean Lifecycle: @PostConstruct and @PreDestroy
  • The Mini Blog Wired by Spring: Plain Java vs Spring, Side by Side
  • Spring MVC and SQLite Without Spring Boot: the Mini Blog in the Browser
  • Your First Spring Boot 4 Project: Create It in IntelliJ, Run It, and the Four Files That Matter
  • What Is Spring Boot? Spring Framework 7 With the Decisions Already Made
  • The Project Context File: AGENTS.md and CLAUDE.md for a Spring Boot Project
  • Plan Before Code: a Five-Part Brief, Plan Mode and /goal for a Spring Boot Feature
  • From Design Frames to Thymeleaf Pages: Briefing an AI Agent for a Spring Boot Blog
  • Add, Edit and Delete Posts With a Rich-Text Editor in Spring Boot: Quill, jsoup and th:utext
  • Profile Page and Photo Upload in Spring Boot: Check the File, Shrink It, Keep Your Own Name
  • Building a Feature With an AI Agent, End to End: Comments on a Spring Boot Blog
  • Containerising Spring Boot: a Layered Dockerfile vs Buildpacks
  • GraalVM Native Image and Spring AOT: When It Pays, and What It Costs
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Scheduled Jobs in Spring Boot: fixedRate, fixedDelay, cron, and ShedLock for Many Instances
  • Redis in Spring Boot: a Cache, a Rate-Limit Counter and a Job Status Hash
  • Actuator and Micrometer in Spring Boot: Health, Your Own Metrics, and the Four Numbers That Matter
  • Structured Logging and Correlation IDs in Spring Boot: JSON Lines, a Filter and the MDC
  • Dashboards and Alerts for a Spring Boot App: Prometheus, Grafana and One Real Incident
  • Finding a Slow Spring Boot Endpoint: Actuator Timers, EXPLAIN ANALYZE and One Index
  • A GitHub Actions Workflow for a Maven Project: Cache, a Java Matrix and Test Reports That Survive a Red Run
  • The AWS SDK for Java v2 in Spring Boot: Clients as Beans, the Default Credentials Chain and No Keys in Code
  • Attachments in S3 from Spring Boot: Pre-signed Uploads, a 302 to a Pre-signed Download, and Links That Expire
  • CloudWatch for a Spring Boot App: JSON Logs, Micrometer Metrics From Your Own Code, and an Alarm That Reaches a Person
  • Automated Deploy, Smoke Test and Rollback for a Spring Boot App: Green Tests Are Not a Working Deploy
  • Environments, Secrets and Approvals in GitHub Actions: One Image From Staging to Production
  • Distributed Tracing Across Spring Boot Services and Kafka: One Trace ID From the Gateway to the Last Reader, Even Through an Outbox
  • Thymeleaf and htmx in Spring Boot: Live Search and One-Row Updates From Server-Rendered Fragments, With No JavaScript Framework
  • Rate Limiting, Backpressure and Load Shedding in Spring Boot: Bucket4j in Redis, a Bounded Worker Pool and Dropping Low-Priority Work
  • Resilience4j in Spring Boot: A Timeout, One Retry, a Circuit Breaker, a Bulkhead and a Fallback, Measured Against a Slow Dependency
  • Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
  • Entities and H2 in Spring Boot: a Post Class Becomes a Table
  • Seed Data and Posts on the Homepage: CommandLineRunner, the Model and th:each
  • Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
  • Connect Spring Boot to PostgreSQL: Driver, application.yml and the Hikari Pool
  • JPA Entity Mapping: Ids, Enums and Dates, From a Java Class to a Table
  • Spring Data Query Methods: Derived Queries, @Query and Projections
  • The N+1 Problem in JPA: Fetch Types, Join Fetch and Entity Graphs
  • Spring @Transactional: All or Nothing, the Proxy, and the Self-Call Trap
  • Flyway Migrations in Spring Boot: Numbered SQL Files, Seed Data and the History Table
  • Spring Data JPA Auditing and Soft Deletes: Who Changed It, When, and Hiding Instead of Deleting
  • Optimistic Locking with @Version: Two Agents, One Ticket, No Lost Update
  • Finding a Slow Spring Boot Endpoint: Actuator Timers, EXPLAIN ANALYZE and One Index
  • Caching With Spring and Redis: Cache-Aside, a TTL per Kind of Data, Eviction on Edit and Stopping the Stampede
  • A PostgreSQL Read Replica in Spring Boot: Route readOnly Transactions, Size the Pool, Find the Index, Read Your Own Writes
  • A Registration Form With Bean Validation in Spring Boot: @Valid, BindingResult and th:errors
  • Spring Security 7 Form Login, BCrypt and a UserDetailsService on the Account Table
  • Roles and Authorities at Login in Spring Security: From a ROLE Column to hasRole("ADMIN")
  • Menus per Role With Thymeleaf Security Tags: sec:authorize, sec:authentication and an Edit Button for the Author
  • Fixing the Access Bugs: a Rule per Role and an Ownership Check in Spring Security
  • Add, Edit and Delete Posts With a Rich-Text Editor in Spring Boot: Quill, jsoup and th:utext
  • Remember Me and Forgot Password by Email in Spring Boot: a Signed Cookie and a One-Time Link
  • Spring Boot Security Defaults: What One Dependency Gives You for Free
  • The Spring Security Filter Chain and Your Own Rules: 401, 403 and Rule Order
  • Stateless JWT Authentication in Spring Security: Sign Once, Check Every Request
  • Users in the Database with Spring Security: Register, BCrypt and Log In
  • Method Security in Spring: @PreAuthorize, Roles and Who Owns This Ticket
  • CORS and CSRF in Spring Security: Why the Browser Blocks Your SPA, and When CSRF Can Be Off
  • Reviewing AI-Written Spring Code for Security: Four Questions for Every Diff
  • Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser
  • An API Gateway With Spring Cloud Gateway: Check the JWT Once at the Edge, Pass the Caller Inward, and Know What the Network Now Trusts
  • Unit Tests With AI for a Spring Boot Service: Mockito Mocks, Given-When-Then and a Green Run
  • Docker for a Spring Boot App: Run the Tests in the Image Build, or Skip Them on Purpose
  • The Test Pyramid in Spring Boot: Unit, Slice and Whole-App Tests
  • Mockito and Test Doubles: Stubs, Mocks and Fakes for One Java Class
  • Spring Boot Test Slices: @WebMvcTest with MockMvc and @DataJpaTest
  • Integration Tests with Testcontainers: A Real PostgreSQL for Every Spring Boot Test Run
  • Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser
  • Test-First with a Coding Agent: Spec, Red Tests, Then the Code
  • Quality and Security Gates for a Maven Project: JaCoCo Coverage, PMD, an SBOM and a Trivy Scan
  • Testing Spring AI Features: a Stub ChatModel, Must-Cite and Must-Refuse Tests, and One Tagged Model Test
  • What Spring AI 2 Is, and Why a Java Team Wants It
  • Spring AI ChatClient: One API for Any Model, and the Model Is a Property
  • Spring AI Prompt Templates: Placeholders, Few-Shot Messages and Versioned Prompt Files
  • Spring AI Structured Output: From Model JSON to a Java Record, and a Real Ticket Triage Feature
  • Streaming Spring AI Answers to the Browser: stream(), a Flux of Server-Sent Events and the Cancel
  • Local Models With Ollama in Spring AI: Profiles, Per-Call Options and What a Smaller Model Costs
  • Testing Spring AI Features: a Stub ChatModel, Must-Cite and Must-Refuse Tests, and One Tagged Model Test
  • Embeddings and pgvector in Spring AI: EmbeddingModel, VectorStore, Distance Operators and the HNSW Index
  • RAG Ingestion in Spring AI: Parse Markdown, Chunk by Section, Embed Into pgvector With Stable Ids
  • Tuning Retrieval in Spring AI: Top-k, a Minimum Score, a Tenant Filter Inside the Query, Hybrid Search and a Reranker
  • Tool Calling in Spring AI 2: @Tool Methods, the ToolCallingAdvisor Loop and a Tool-Call Limit
  • Chat Memory in Spring AI: MessageChatMemoryAdvisor, a Conversation Id, a Window, a Summary and Where the State Lives
  • Building an MCP Server in Java With Spring AI: @McpTool, Stateless Streamable HTTP and Least-Privilege Tools
  • Consuming MCP Servers From Spring AI: a stdio Child Process and a Remote Streamable HTTP Server, Compared
  • A Supervisor and Specialist Agents in Spring AI: Own Prompts, Own Tools, Explicit State and a Menu Checked in Code
  • Choosing a JVM Agent Framework: the Same Two-Step Triage in Spring AI, LangChain4j Agentic and Embabel
  • Observability for Spring AI Calls: a Span per Feature, Token and Spend Counters, Jaeger Traces and Two Prometheus Alerts
  • Evals and Cost Control for a Java Subtitle Service: A Golden Set Scored by Word Error Rate in CI, and the Cost of One Hour of Audio From Micrometer Meters
  1. Blog
  2. /
  3. Spring Boot
  4. /
  5. Data Access and JPA

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Data Access and JPA

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.

Relay's layers: our code at the top, then repository and entities (later), then JdbcTemplate with the Hikari pool holding ten connections, then PostgreSQL 18 at the bottom. Our code: RelayApplication, ConnectionCheck Repository and entities (later in the section) JdbcTemplate + Hikari pool 10 open connections PostgreSQL 18 (Docker, port 5432) database relay, user relay
Today's work is the connection between our code and PostgreSQL. The pool sits in the middle and keeps the open connections.

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.

One call: ConnectionCheck calls queryForObject, JdbcTemplate borrows a connection from the pool (idle 10 to 9), the select goes to PostgreSQL, the row comes back, the connection is returned (idle 9 to 10). ConnectionCheckqueryForObject JdbcTemplate Hikari poolidle 10 → 9 → 10 PostgreSQL callborrowselect Stringreturn1 row Opening a connection is slow, so the pool opens ten once and lends them out.
Every call goes down and comes back. The pool lends a connection and takes it back.

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 localhost inside 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, a docker compose down takes your rows with it.

Recap

PieceWhereJob
db servicecompose.yamlruns postgres:18 with a user, a database and a volume
Driverpom.xml, scope runtimetalks PostgreSQL's protocol
Datasourceapplication.ymlURL and login, dev defaults, strict prod profile
Hikari poolbuilt by Spring Bootkeeps 10 connections open and lends them
JdbcTemplateyour codeborrows 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Spring Boot · 45 of 99

Previous
Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
Next post
JPA Entity Mapping: Ids, Enums and Dates, From a Java Class to a Table

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.

On this page

  • Where this sits in Relay
  • One compose service: PostgreSQL is running
  • One new line in the pom: the driver
  • application.yml: URL, login and two profiles
  • Ask the server who it is
  • One call, through the pool
  • Break it: one letter off in the password
  • Common mistakes
  • Recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.