PostgreSQL is a great database to use with Spring Boot Project. It is fast, reliable and convenient to use with Spring Boot. In this blog, you will learn how to integrate postgres database in spring boot project. How to edit and add configuration in file for connecting postgres database with spring boot project.

I assume that, you have create a project or you can create a simple project using following link. Also refer this blog to Install PostgreSQL Database.

How to Connect PostgreSQL Database in Spring Boot Project

Create Database in PostgresSQL

Use the bellow commands to create the database in Postgres. You can change the database name and db username as per your choice. In this demo project, we are keeping database name as myproject, username as myuser and password as password.

sudo -u postgres psql
CREATE USER myuser WITH PASSWORD 'password';
ALTER ROLE myuser SET client_encoding TO 'utf8';
ALTER ROLE myuser SET default_transaction_isolation TO 'read committed';
ALTER ROLE myuser SET timezone TO 'UTC';

PostgreSQL Driver and JPA Dependency in Spring Boot Project

PostgreSQL Driver: A JDBC and R2DBC driver that allows Java programs to connect to a PostgreSQL database using standard, database independent Java code.

Spring Data JPA: Persist data in SQL stores with Java Persistence API using Spring Data and Hibernate.

In your spring boot project, add the PostgreSQL driver and JPA dependency inside dependencies section in pom.xml or



Once you added the dependecies, resync the maven or graddle, to download the dependencies.

Configure SQL Setting in Spring Boot

Now you just need to add the configuration in your Add the bellow settings and change the database name, user and password accordingly.

#--------------------- DB Connection ------------------

#--------------------JPA-ORM Properties-----------------

Done! now just go and run your project. For creating models, you can refer a small example bellow –

@Entity(name = "users")
public class User {

    @SequenceGenerator(name = "users_sequence", sequenceName = "users_sequence", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "users_sequence")
    private Long id;

    @Column(nullable = false, length = 20)
    private String firstName;

    @Column(nullable = false, length = 20)
    private String lastName;

    @Column(nullable = false, unique = true, length = 45)
    private String email;

    @Column(nullable = false, length = 64)
    private String password;

    @Column(nullable = false, unique = true)
    private String phoneNumber;