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.

Prerequisites:

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;

\q

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 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.6.0</version>
</dependency>

For Gradle project, add the following dependency:

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

// https://mvnrepository.com/artifact/org.postgresql/postgresql
implementation group: 'org.postgresql', name: 'postgresql', version: '42.6.0'

Step 3: Configure application.properties file for Spring Boot Postgres Connection

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

For application.properties

spring.datasource.url=jdbc:postgresql://localhost:5432/your_database_name
spring.datasource.username=your_database_username
spring.datasource.password=your_database_password
spring.datasource.driver-class-name=org.postgresql.Driver

# This will create table automatically in your database
spring.jpa.hibernate.ddl-auto=create

For application.yml:

spring:
    datasource:
        driver-class-name: org.postgresql.Driver
        password: your_database_password
        url: jdbc:postgresql://localhost:5432/your_database_name
        username: your_database_username
    jpa:
        hibernate:
            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 User.java:

import jakarta.persistence.*;

@Entity
@Table(name = "users")
public class User {
    @Id
    @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) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

Step 5: Create a Repository

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

import org.springframework.data.jpa.repository.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:

UserService.java:

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

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

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    // Create a new user
    public User createUser(User user) {
        return userRepository.save(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();
            existingUser.setName(userDetails.getName());
            existingUser.setEmail(userDetails.getEmail());
            return userRepository.save(existingUser);
        }
        return null;
    }

    // Delete all users
    public void deleteAllUsers() {
        userRepository.deleteAll();
    }

    // Delete user
    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }

    // Other business logic related to users
}

UserController.java:

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

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

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

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

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

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

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

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

    // Delete user by ID
    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUser(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.

Conclusion

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