How To Use PostgreSQL Database With Spring Boot

connecting PostgreSQL database with spring boot

Spring Boot can be used with variety of different databases. Spring Boot provides powerful auto-configuration capabilities that make it easy to set up and configure a database connection in your application. In this blog we will learn How To Use PostgreSQL Database With Spring Boot.

What is PostgreSQL?

PostgreSQL, often referred to as Postgres, is a powerful open-source relational database management system (RDBMS). It is designed to store, manage, and retrieve structured data efficiently and securely. PostgreSQL is known for its reliability, extensibility, and adherence to SQL standards.

Steps to Configure PostgreSQL with Spring Boot:

1. Include the necessary dependencies:

In your Spring Boot project’s pom.xml (Maven) or build.gradle (Gradle) file, add the required dependencies for Spring Data JPA and PostgreSQL. Here’s an example for
Maven:

<dependencies>
    <!-- Other dependencies -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

Make sure to replace <version> with the appropriate version number.

2. Configure the database connection:

In your application.properties or application.yml file, provide the necessary configuration for connecting to your PostgreSQL database. Here’s an example using application.properties:

spring.datasource.url=jdbc:postgresql://localhost:5432/db_name
spring.datasource.username=db_username
spring.datasource.password=db_password
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect

Replace db_name, db_username, and db_password with your actual database name, username, and password, respectively. Adjust the spring.datasource.url based on your PostgreSQL server configuration.

3. Define the Entity class:

Create a Java class representing the entity/table you want to interact with in the database. Annotate the class with @Entity and use other JPA annotations like @Id, @Column, etc., to map the class attributes to the corresponding database columns.

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class MyEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    // Getters and setters
}
4. Create a Repository interface:

Define a repository interface by extending JpaRepository or one of its subinterfaces. This will provide standard CRUD operations and additional querying capabilities.

import org.springframework.data.jpa.repository.JpaRepository;

public interface MyEntityRepository extends JpaRepository<MyEntity, Long> {
    // Additional custom query methods can be defined here
}
5. Use the Repository in your application:

You can now use the repository to perform database operations in your application. Inject the repository into your service or controller classes using @Autowired or constructor injection.

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

@Service
public class MyService {
    private final MyEntityRepository repository;

    @Autowired
    public MyService(MyEntityRepository repository) {
        this.repository = repository;
    }

    // Use repository methods to interact with the database
}

You can also use the repository directly in your controller classes to handle incoming requests and manage data persistence.

Learn with Example:

Create a new Spring Boot project:

Start by creating a new Spring Boot project using your preferred IDE or the Spring Initializr (https://start.spring.io). Make sure to include “spring-boot-starter-data-jpa” and “postgresql” dependencies.

Configure the database connection:

Open the application.properties file and provide the following configuration for connecting to PostgreSQL:

spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=myuser
spring.datasource.password=mypassword
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect

Adjust the values according to your PostgreSQL setup.

Create an Entity class:

Create a Java class to represent an entity/table in the database. Let’s create a simple Book entity with an id and title attribute.

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;

    // Constructors, getters, and setters
}

Define a Repository interface:

Create a repository interface to handle database operations for the Book entity.

import org.springframework.data.jpa.repository.JpaRepository;

public interface BookRepository extends JpaRepository<Book, Long> {
}

The JpaRepository interface provides standard CRUD operations and querying capabilities for the Book entity.

Use the Repository in your application:

Let’s create a simple BookService class that utilizes the BookRepository to perform database operations.

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

import java.util.List;

@Service
public class BookService {
    private final BookRepository bookRepository;

    @Autowired
    public BookService(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }

    public List<Book> getAllBooks() {
        return bookRepository.findAll();
    }

    public Book createBook(Book book) {
        return bookRepository.save(book);
    }

    // Other methods for updating, deleting, or retrieving books
}

In this example, the BookService class uses the bookRepository to perform operations such as retrieving all books or creating a new book.

Create a REST Controller:

Create a REST controller to expose the BookService methods as API endpoints.

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

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    private final BookService bookService;

    @Autowired
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @GetMapping
    public List<Book> getAllBooks() {
        return bookService.getAllBooks();
    }

    @PostMapping
    public Book createBook(@RequestBody Book book) {
        return bookService.createBook(book);
    }

    // Other methods for updating, deleting, or retrieving books
}

This controller maps the GET and POST requests to retrieve all books or create a new book, respectively.

Run the application:

Start the Spring Boot application, and it will automatically create the necessary tables in the PostgreSQL database based on the entity mappings. You can then access the REST API endpoints defined in the BookController class to interact with the database.

Official Documentation: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#data.sql