Connect PostgreSQL in Spring Boot: Maven & Gradle Configuration

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 steps to connect PostgreSQL with 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. PostgreSQL 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.

Step 1: Set up PostgreSQL Database

Make sure you have PostgreSQL installed and running. Create a new database for your Spring Boot 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 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 use Postgres in your Spring Boot project, you need to include the JPA and MySQL JDBC driver as a dependency in your project’s build file (pom.xml for Maven or build.gradle for Gradle). The JDBC driver enables Java applications to interact with Postgres databases.

For Maven users, add the following dependency:

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

<!-- -->

For Gradle users, 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 DataSource Properties

In the “” (or “application.yml”) file of your Spring Boot project, 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.

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. You can run your Spring Boot application. The application will start, and you should be able to access the REST endpoints defined in the BookController. For example, you test it in Postman:

  • 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": "Huzaif", "email": "[email protected]" }
  • To update a user: PUT http://localhost:8080/users
  • To delete all users: DELETE http://localhost:8080/users
  • To delete book 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 scalble Java applications using Spring Boot and PostgreSQL.

Find this Project in Github.

You can also read our Blog on Best Practices for Folder Structure in SpringBoot.

Also Read How to Protect Sensitive Data in a Java Project Like Spring Boot.

Read our Blog on How to Provide Initial Default Data for Models in Spring Boot