Connecting to PostgreSQL
In our previous lesson, we set up a PostgreSQL database using Docker Compose.
Now we'll configure our Spring Boot application to connect to this database.
Database Configuration
Spring Boot uses the application.properties file to manage database connection settings.
Create or open src/main/resources/application.properties and add these properties:
# Database Connection
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=changemeinprod!
# JPA Configuration
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialectUnderstanding the Configuration
The database URL follows a specific format that tells Spring how to connect to our PostgreSQL instance.
The spring.jpa.hibernate.ddl-auto=update setting enables Hibernate to automatically update the database schema based on our entity classes.
The show-sql and format_sql properties help during development by logging SQL statements to the console.
Summary
- Spring Boot auto-configures most database connection properties
- The
application.propertiesfile centralizes database configuration - Hibernate's
ddl-auto=updatemode automatically manages schema changes