You are currently viewing Spring Boot and PostgreSQL Integration
Deploy Spring Boot App with PostgreSQL on Render

Spring Boot and PostgreSQL Integration

If you’re working on a Spring Boot application and want to connect it to a PostgreSQL database, this guide is for you. we will configure postgresql to an existing web application and testing the connection via a browser. On this article, you will get a sample Dockerfile that can be used to dockerize your application.

The referenced project in this blog article can be found here: https://github.com/danielnjama/spring-boot-and-postgresql

Step 1: Add Required Maven Dependencies

In your pom.xml, add the following highlighted inside the dependency tag:

<!-- Spring Boot Web -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- Spring Boot Thymeleaf -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<!-- ✅ Spring Data JPA: handles database interactions-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- ✅ PostgreSQL Driver- Refers to the database in Use -->
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.7.3</version>
</dependency>

Step 2: Configure PostgreSQL in application.properties

Add your database credentials to src/main/resources/application.properties: Replace localhost, 5432, your_database_name, your_username, and your_password accordingly.

spring.datasource.url=jdbc:postgresql://localhost:5432/your_db_name
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=org.postgresql.Driver

# Hibernate settings (optional but useful)
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

Step 3: Create the TestRecord Entity

Create the file TestRecord.java inside model/: Models folder may not exist. In my case, I will create one at the following path: src/main/java/com/dtechnologys/dtect_springboot/model/TestRecord.java

package com.dtechnologys.dtect_springboot.model;

import jakarta.persistence.*;

@Entity
public class TestRecord {

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

    private String message;

    public TestRecord() {}

    public TestRecord(String message) {
        this.message = message;
    }

    // Getters and setters
    public Long getId() {
        return id;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

Step 4: Create a Repository Interface

Inside repository/, create a repository interface. I will create one under the path: src/main/java/com/dtechnologys/dtect_springboot/repository/TestRecordRepository.java and add the following

package com.dtechnologys.dtect_springboot.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import com.dtechnologys.dtect_springboot.model.TestRecord;

public interface TestRecordRepository extends JpaRepository<TestRecord, Long> {
}

Step 5: Update the Controller

Here’s the complete controller update: Update the controller under which you are managing the routes for your application.

package com.dtechnologys.dtect_springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dtechnologys.dtect_springboot.model.TestRecord;
import com.dtechnologys.dtect_springboot.repository.TestRecordRepository;

@Controller
public class HomeController {

    @Autowired
    private TestRecordRepository testRecordRepository;

    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("title", "Home Page");
        return "home";
    }

    @GetMapping("/contacts")
    public String contacts(Model model) {
        model.addAttribute("title", "Contacts Page");
        return "contacts";
    }

    @GetMapping("/db-test")
    @ResponseBody
    public String testDatabaseConnection() {
        TestRecord record = new TestRecord("Testing DB connection");
        testRecordRepository.save(record);

        long totalRecords = testRecordRepository.count();
        return "DB connection successful! Total records: " + totalRecords;
    }

    @GetMapping("/db-test-page")
    public String testDatabasePage(Model model) {
        TestRecord record = new TestRecord("Test from template");
        testRecordRepository.save(record);

        long totalRecords = testRecordRepository.count();
        model.addAttribute("message", "DB connected! Total records: " + totalRecords);
        return "db-test";
    }
}

Step 6: Create the db-test.html Template

Under templates- location where other templates are being managed create db-test.html template. See the path: src/main/resources/templates/db-test.html, and add the db test information. see below:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Database Test</title>
</head>
<body>
    <h1 th:text="${message}"></h1>
    <a href="/">Back to Home</a>
</body>
</html>

Testing the Setup.

Run the following to install the necessary updates and create a build of your application

mvn clean install

Start your app with the following command:

mvn spring-boot:run

Once the server has started, proceed to test for database connection. In this case, we will visit the db test page. In your case, you can test adding and retriving data from the database. The web application should be accessible on localhost and port 8080 unless a different port has been set.

http://localhost:8080/db-test-page    #HTML-rendered DB result

Once this has confirmed a success, proceed and add the necessary web logic to save and retrive data from your database.

Note:

  1. Running the command: mvn spring-boot:run create the project buld as a .jar file under target directory. This .jar file is used to deploy this application on various platforms.
  2. To create a docker container for your Springboot project, see the Dockerfile sample below. Confirm the name of the .jar file under the target folder and the version of Java and adjust accordingly.
FROM openjdk:17-jdk-alpine

WORKDIR /app

COPY target/dtect-springboot-0.0.1-SNAPSHOT.jar app.jar

EXPOSE 8080

CMD [ "java", "-jar", "app.jar" ]
docker build -t docker-hub-username/image-name
docker push docker-hub-username/image-name

Make a donation to support us


Web Hosting and email hosting Packages


For web development services, SEO services, Digital marketing strategies, website set up services, web hosting and domain registration; contact Dynamic Technologies.


Related articles:

  1. How-to-install-docker-on-Linux
  2. Getting Started with Docker | Docker commands
  3. How To Deploy a Spring Boot Application
  4. A Practical Tutorial for Dockerizing Software Applications