Sub topic 3
Configuring the database connection
This chapter shows how the Book API connects to a database. You will set up PostgreSQL for real use and H2 for local development, and you will choose how Hibernate treats the schema. This chapter assumes you can read a Spring Boot application.properties file and know what a JDBC URL is. It also assumes you have a Maven project with the starters from the previous chapter and a Docker installation (or a local PostgreSQL server) to run against.
What Spring Boot configures for you
You never create a database connection yourself in this tutorial. Spring Boot's auto-configuration looks at the classpath and the spring.datasource.* properties, then builds three things:
- A
DataSource, backed by the HikariCP connection pool. - A JPA
EntityManagerFactory, which is Hibernate configured with thatDataSource. - A transaction manager that
@Transactionaluses.
If no spring.datasource.url is set and an embedded database such as H2 is on the classpath, Boot starts an in-memory database for you. That is convenient for a first run. It is also a common source of confusion, because your data disappears on restart and you may not notice that the app never talked to your real database.
Adding the PostgreSQL driver
The starter list from the setup chapter includes H2 but no PostgreSQL driver. Add the driver to pom.xml. The Spring Boot parent manages its version.
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>The runtime scope is enough because your code never imports driver classes. JDBC loads the driver from the URL prefix jdbc:postgresql:.
The core properties
Put this in src/main/resources/application.properties:
spring.datasource.url=jdbc:postgresql://localhost:5432/books
spring.datasource.username=${DB_USER}
spring.datasource.password=${DB_PASSWORD}
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.open-in-view=falseEach line does one job:
spring.datasource.urlis the JDBC URL. Its parts are the protocol (jdbc:postgresql), the host (localhost), the port (5432), and the database name (books).usernameandpassworduse${...}placeholders. Spring resolves them from environment variables, system properties, or other property sources at startup. Credentials stay out of source control.ddl-auto=validatetells Hibernate to compare your entities with the existing schema and fail at startup if they disagree. It never changes the database.open-in-view=falseis explained below.
Spring Boot also accepts environment variables directly through relaxed binding. Setting SPRING_DATASOURCE_URL overrides spring.datasource.url without any placeholder in the file. The placeholder style used here makes it obvious which values the app expects.
Starting a local PostgreSQL
If you have no PostgreSQL server, run one in Docker. The database name must match the URL above.
docker run --name books-db -d -p 5432:5432 \
-e POSTGRES_DB=books \
-e POSTGRES_USER=books \
-e POSTGRES_PASSWORD=change-me \
postgres:16
export DB_USER=books
export DB_PASSWORD=change-meThe two export lines set the variables that the placeholders read. They apply only to the current shell, so run the application from the same terminal.
Choosing a ddl-auto value
spring.jpa.hibernate.ddl-auto controls whether Hibernate touches the schema at startup.
| Value | Behavior | Typical use |
|---|---|---|
| `none` | Does nothing. | Production with managed migrations |
| `validate` | Checks that tables and columns match the entities, and fails if not. | Production and staging |
| `update` | Adds missing tables and columns, never removes anything. | Quick experiments only |
| `create` | Drops and recreates the schema at startup. | Throwaway test databases |
| `create-drop` | Like `create`, and drops the schema at shutdown. | In-memory development databases |
Avoid update outside experiments. It cannot rename or remove columns, it gives no record of what it changed, and it can produce a schema that differs between environments. create and create-drop erase data, so a wrong profile or URL can destroy a real database.
The trade-off with validate is that something else must create the schema first. For a real project, use a migration tool such as Flyway or Liquibase, which applies versioned SQL files in order. With Flyway you add its Spring Boot dependencies and place scripts in src/main/resources/db/migration. Boot runs them before Hibernate validates. A first migration for this tutorial could be V1__create_book.sql:
create table book (
id bigint generated by default as identity primary key,
title varchar(255),
author varchar(255)
);This matches the Book entity. Long id maps to bigint, with GenerationType.IDENTITY relying on the identity column. String fields map to varchar(255) by default. If you run the application against an empty database with validate and no migration, it stops with a SchemaManagementException such as missing table [book]. That failure is intentional, and it is better than discovering a wrong schema at the first request.
A development profile with H2
Typing credentials and starting Docker for every quick experiment gets tedious. A Spring profile lets you keep a second set of properties for development. Create src/main/resources/application-dev.properties:
spring.datasource.url=jdbc:h2:mem:books;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=trueProperties in this file override those in application.properties when the dev profile is active. Activate it from the command line:
SPRING_PROFILES_ACTIVE=dev ./mvnw spring-boot:runDetails worth knowing:
jdbc:h2:mem:bookscreates an in-memory database namedbooks.DB_CLOSE_DELAY=-1keeps it alive while the JVM runs. Without it, H2 can discard the database when the last connection closes.- With
create-drop, Hibernate builds thebooktable from the entity, so you need no migration for development. show-sql=trueprints each SQL statement. It is useful for learning what repository calls do, and too noisy for production.- The profile file leaves
${DB_USER}unused, so the app starts without those variables set.
H2 is not PostgreSQL. SQL dialect differences, locking behavior, and type handling can hide bugs that appear only on the real database. Use H2 for fast feedback, and run your integration tests against PostgreSQL before release. Testcontainers is a common way to do that.
Why open-in-view is off
By default Spring Boot enables Open Session in View. It keeps a Hibernate session and a database connection open for the whole HTTP request, including JSON serialization in the controller. This lets lazy-loaded fields load late, but it has costs:
- A connection stays checked out while the response is written, which can exhaust the pool under load.
- Database queries can happen in the web layer, outside any service transaction.
- Boot logs a warning at startup when the property is left at its default.
Setting it to false forces data loading to finish inside the service, which is where this tutorial puts transactions. The BookResponse DTO also removes any need for lazy loading in the controller.
Tuning the connection pool
HikariCP defaults work for a small service. The properties you may adjust first:
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.connection-timeout=30000maximum-pool-size is the number of connections the pool will open. Each connection uses memory on the database server, and PostgreSQL has its own limit (max_connections, 100 by default). If you run several application instances, the sum of all their pools must stay below that limit. connection-timeout is how many milliseconds a request waits for a free connection before it fails.
Common startup errors
| Message (shortened) | Likely cause | Fix |
|---|---|---|
| `Could not resolve placeholder 'DB_USER'` | The environment variable is not set in the shell that launched the app. | Export it, or set it in your IDE run configuration. |
| `Connection refused` | PostgreSQL is not running, or the host or port is wrong. | Check `docker ps` and the URL. |
| `password authentication failed for user` | Credentials differ from what the database was created with. | Compare with the `POSTGRES_USER` and `POSTGRES_PASSWORD` values. |
| `database "books" does not exist` | The URL names a database that was never created. | Create it, or set `POSTGRES_DB` on first container start. |
| `Schema-validation: missing table [book]` | `validate` is on but no schema exists. | Add a migration, or use the `dev` profile. |
| `Schema-validation: wrong column type` | The entity and the table disagree. | Change the entity or add a migration that fixes the column. |
Exercise
You deploy the Book API to staging with spring.jpa.hibernate.ddl-auto=validate and an empty PostgreSQL database. The application fails at startup with missing table [book]. Name two ways to fix this without changing the validate setting, and say which you prefer for a long-lived project.
Show answer
Create the table before startup, either by running a SQL script by hand or by adding a migration tool such as Flyway with a V1__create_book.sql file that Boot applies before Hibernate validates. For a long-lived project, prefer the migration tool. It records every schema change in versioned files, applies them the same way in every environment, and keeps the schema reproducible. Hand-run scripts are easy to forget or apply inconsistently.