How to Connect PostgreSQL in Spring Boot with Example

Spring Boot is a popular framework for building Java applications, and PostgreSQL is a powerful open-source relational database management system. Combining the two can provide a robust and efficient solution for data persistence in your Java applications. In this blog, we will walk you through the tutorial steps for How to connect PostgreSQL in Spring Boot, along with a practical example.


Before we begin, make sure you have the following prerequisites in place:

  1. Java Development Kit (JDK) installed on your system
  2. An Integrated Development Environment (IDE) like Eclipse or IntelliJ IDEA
  3. Postgres database installed and running
  4. Spring Boot project set up (if not, you can quickly set it up using the Spring Initializr)

Note: For this tutorial, we are using our basic skeleton project for springboot. You can also download the project from here.

How to Connect Spring Boot with Postgres Database

Step 1: Set up PostgreSQL Database

Make sure you have PostgreSQL installed and running. Create a new database for your springboot application using the PostgreSQL interactive terminal or a GUI tool like pgAdmin. Note down the database name, username, and password, as we will need these credentials configuration to connect from Spring Boot.

sudo -u postgres psql

CREATE DATABASE your_database_name;
CREATE USER your_username WITH PASSWORD 'your_password';
GRANT ALL PRIVILEGES ON DATABASE your_database_name TO your_username;


Step 2: Add PostgreSQL Dependency to pom.xml or build.gradle

To connect spring boot to postgresql, you need to include the JPA and postgresql driver as a dependency in your project’s build file (pom.xml for Maven or build.gradle for Gradle). The driver enables Java applications to interact with Postgres databases.

For Maven application, add the following dependency:

<!-- Add the Spring Data JPA starter dependency -->

<!-- -->

For Gradle project, add the following dependency:

// Add the Spring Data JPA starter dependency
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

implementation group: 'org.postgresql', name: 'postgresql', version: '42.6.0'

Step 3: Configure file for Spring Boot Postgres Connection

In the “” (or “application.yml”) file of your Java Spring Boot application, add the following configuration to connect to the PostgreSQL database:



# This will create table automatically in your database

For application.yml:

        driver-class-name: org.postgresql.Driver
        password: your_database_password
        url: jdbc:postgresql://localhost:5432/your_database_name
        username: your_database_username
            ddl-auto: create

Make sure to replace “your_database_name,” “your_database_username,” and “your_database_password” with your actual PostgreSQL database credentials.

Up to this point, your postgres database should be connected to the Spring Boot application. You can run the application and check if there are no errors.

For better understanding, we are using the user model example use case, and you can apply this same logic to building up different use cases.

Step 4: Create a Data Model

Create a simple data model class representing the table you want to interact with in the database. For example, let’s create a “User” model with file name

import jakarta.persistence.*;

@Table(name = "users")
public class User {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String email;

    // Constructors, Getters, and Setters
    public Long getId() {
        return id;

    public void setId(Long id) { = id;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public String getEmail() {
        return email;

    public void setEmail(String email) { = email;

Step 5: Create a Repository

Next, create a Spring Data JPA repository “” for the “User” model to perform database operations. This interface extends the JpaRepository:


public interface UserRepository extends JpaRepository<User, Long> { }

Step 6: Implement Business Logic (Service and Controller)

Now, let’s create a service and a controller to handle the business logic and expose the endpoints respectively. For brevity, we’ll only include the essential parts here:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

public class UserService {
    private UserRepository userRepository;

    // Create a new user
    public User createUser(User user) {

    // Get all users
    public List<User> getAllUsers() {
        return userRepository.findAll();

    // Get user by ID
    public Optional<User> getUserById(Long id) {
        return userRepository.findById(id);

    // Update user
    public User updateUser(Long id, User userDetails) {
        Optional<User> user = userRepository.findById(id);
        if (user.isPresent()) {
            User existingUser = user.get();
        return null;

    // Delete all users
    public void deleteAllUsers() {

    // Delete user
    public void deleteUser(Long id) {

    // Other business logic related to users

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

public class UserController {
    private UserService userService;

    // Create a new user
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);

    // Get all users
    public List<User> getAllUsers() {
        return userService.getAllUsers();

    // Get user by ID
    public Optional<User> getUserById(@PathVariable Long id) {
        return userService.getUserById(id);

    // Update user by ID
    public User updateUser(@PathVariable Long id, @RequestBody User userDetails) {
        return userService.updateUser(id, userDetails);

    // Delete all users
    public String deleteAllUsers() {
        return "All users have been deleted successfully.";

    // Delete user by ID
    public void deleteUser(@PathVariable Long id) {

Step 7: Run and Test the Application

Now, you have completed the setup for spring boot connect to postgres. You can run your Spring Boot project. The application will start, and you should be able to access the REST endpoints defined in the UserController. For example, you can test it in Postman or curl:

  • To get all users: GET http://localhost:8080/users
  • To add a user: POST http://localhost:8080/users with a JSON body containing book details – { "name": "your_name", "email": "[email protected]" }
  • To update a user: PUT http://localhost:8080/users
  • To delete all users: DELETE http://localhost:8080/users
  • To delete user by idDELETE http://localhost:8080/users/{id}

Note: You can create your HTML Form, submitting and displaying data.


Congratulations! You have successfully connected PostgreSQL with Spring Boot, allowing your application to store and retrieve data from the database. With this blog, you can now build robust and scalable Java applications using Spring Boot PostgreSQL.

Find this Project in Github.

Read our blog on How to Migrate Data from SQLite to PostgreSQL and MySQL in Django with Example