How to Connect PostgreSQL Database with Spring Boot

Introduction :

Database connectivity is one of the most important aspects of any Spring Boot application. Whether you are building a REST API, an e-commerce platform, or an enterprise application, you need a database to store and retrieve data.

In this article, we will learn how to connect a PostgreSQL database with a Spring Boot application using Spring Data JPA.



Why PostgreSQL?

PostgreSQL is a powerful open-source relational database known for its reliability, performance, and advanced features. It is widely used in enterprise applications and works seamlessly with Spring Boot.

Benefits of PostgreSQL

  • Open-source and free

  • High performance

  • ACID compliant

  • Supports complex queries

  • Enterprise-grade security

Prerequisites

Before getting started, make sure you have:

  • Java 17 or later

  • Spring Boot 3.x

  • PostgreSQL Installed

  • Maven

  • IDE (IntelliJ IDEA, Eclipse, or VS Code)

Step 1: Create a PostgreSQL Database

Open PostgreSQL and create a database:

CREATE DATABASE springboot_db;

Verify that the database has been created successfully.

Step 2: Add Required Dependencies

Add the following dependencies to your pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
</dependency>

Step 3: Configure Database Properties

Add the following configuration to application.properties:

spring.datasource.url=jdbc:postgresql://localhost:5432/springboot_db
spring.datasource.username=postgres
spring.datasource.password=password

spring.datasource.driver-class-name=org.postgresql.Driver

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

Property Explanation

  • spring.datasource.url → Database connection URL

  • spring.datasource.username → PostgreSQL username

  • spring.datasource.password → PostgreSQL password

  • ddl-auto=update → Automatically updates tables

  • show-sql=true → Displays SQL queries in console

Step 4: Create an Entity Class

@Entity
@Table(name = "employee")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String department;

    // Getters and Setters
}

Instead of manualy writing getter and setter methods, we can use Lombok Annotations such as @Getter
and @Setter. Otherwise we can use @Data Annotation.

It helps reduce boilerplate code and improves readability, especially in large Spring Boot applications.

Step 5: Create Repository Interface

@Repository
public interface EmployeeRepository
        extends JpaRepository<Employee, Long> {
}

Spring Data JPA automatically provides CRUD operations.

Step 6: Run the Application

Start the Spring Boot application.

If the configuration is correct:

  • Application starts successfully

  • Database connection is established

  • Employee table is created automatically

How Spring Boot Connects to PostgreSQL

  1. Spring Boot reads datasource properties.

  2. Creates a database connection.

  3. Hibernate initializes entity mappings.

  4. Tables are created or updated.

  5. Application interacts with PostgreSQL through JPA repositories.

Understanding Key JPA Annotations

  • @Entity : Marks a class as a JPA entity.
  • @Table : Maps the entity to a database table.
  • @Id : Defines the primary key.
  • @GeneratedValue : Generates primary key values automatically.
  • @Column : Maps a field to a table column.

The following annotations are commonly used while creating JPA entities:

These annotations help Hibernate understand how Java objects should be mapped to database tables.

Why Use Spring Data JPA with PostgreSQL?

Benefits :
  • Reduces boilerplate code
  • Automatic table creation and updates
  • Easy CRUD operations
  • Integration with Hibernate
  • Improved developer productivity

Spring Data JPA works seamlessly with PostgreSQL and provides an easy way to interact with relational databases.

Common Errors and Solutions

1. Connection Refused

Cause:
PostgreSQL server is not running.

Solution:
Start PostgreSQL service.

2. Password Authentication Failed

Cause:
Incorrect username or password.

Solution:
Verify database credentials.

3. Database Does Not Exist

Cause:
Incorrect database name.

Solution:
Create the database or update the URL.

Real-World Use Cases

PostgreSQL is commonly used in:

  • Banking Applications

  • E-Commerce Platforms

  • Healthcare Systems

  • Enterprise Applications

  • Learning Management Systems

Common Interview Questions

1. Why is PostgreSQL preferred in enterprise applications?

Because it is reliable, scalable, secure, and supports advanced database features.

2. What is Spring Data JPA?

Spring Data JPA simplifies database operations by reducing boilerplate code.

3. What does ddl-auto=update do?

It automatically updates database tables based on entity changes.

4. Which dependency is required for PostgreSQL?

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
</dependency>

5. What is the default PostgreSQL port?

5432 port

Conclusion :

Connecting PostgreSQL with Spring Boot is straightforward using Spring Data JPA. By configuring datasource properties and adding the required dependencies, developers can quickly establish database connectivity and focus on building business logic.

What's Next?

In this article, we learned how to connect a PostgreSQL database with a Spring Boot application using Spring Data JPA.

In the next article, we will learn how to create JPA Entity and Repository classes in Spring Boot and understand how they interact with PostgreSQL databases to perform data operations efficiently.

Comments

Popular posts from this blog

React Basics – How to Create Component

How to Build REST API using Spring Boot (Step-by-Step Guide)

Spring Boot @RequestParam Annotation Explained with Real-Time Examples