How to integrate SpringBoot 2.x with PostgreSQL database using Spring JPA

How to integrate SpringBoot and PostgreSQL? It is the one of most common questions for developers. So in the post, I will help you to try it with Spring JPA. Here is a to do list for the tutorial:

  • Overview of Project Structure
  • Create SpringBoot with Spring Data JPA and PostgreSQL dependencies
  • Configuration SpringBoot to connect to PostgreSQL
  • Define a data model to map with table’s columns in PostgreSQL database
  • Define a JPA Repository to do CRUD operations
  • Use CommandLineRunner to excute above JPA Repository APIs: save, retrieve, update, detele entities

To do the tutorial, you need prepare Java >= 1.8, Spring Tool Suite in local computer for development.

Let’s go !

Video Guide

SpringBoot Project Overview

Project Overview How to Integrate Springboot 2.x with PostgreSQL using Spring JPA

In the SpringBoot application, we use Spring JPA to connect and manipulate the data between Application and PostgreSQL database. We define a repository to do CRUD operations (save, retrieve, update, delete) with entities. And for mapping the data between Spring Application with database table’s columns, we define a model class.

Create SpringBoot Project

We use Eclipse that had integrated with SpringToolSuite to create a SpringBoot project. Remember we need add 2 dependencies Spring Data JPA and PostgreSQL driver.

Checking pom.xml file we see the needed dependencies as below:


Now we implement a SpringBoot Application to manipulate data with PostgreSQL database.

springboot project structure
SpringBoot project structure

Setup SpringBoot datasource for connecting with PostgreSQL

SpringBoot helps us to create a datasource by simple configuration in file. We use the spring.datasource.* to setup the url, username and password for Spring datasource bean as above.

## PostgreSQL
#drop & create table again, good for testing, comment this in production

How to create a Spring data model class?

Imagine that we have a customer table in PostgreSQL database with 4 columns:
{id, firstname, lastname, age}

How to map the data between SpringBoot application with these table’s columns for manipulating data? We need create a Customer model class having 4 properties {id, firstname, lastname, age} then use annotations to handle the mapping each columns of tables which corresponding properties in java model class.

package com.loizenjava.postgresqlspringboot.model;

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

public class Customer {
	@GeneratedValue(strategy = GenerationType.AUTO)
	private long id;
	private String firstname;
	private String lastname;
	private int age;

	public void setFirstname(String firstname) {
		this.firstname = firstname;
	protected Customer() {}
	public Customer(String firstname, String lastname, int age) {
		this.firstname = firstname;
		this.lastname = lastname;
		this.age = age;
	public String toString() {
		return String.format("id=%d, firstname='%s', lastname'%s', age=%d", 
								id, firstname, lastname, age);	

@Entity specifies that the class is an entity. This annotation is applied to the entity class.
@Table specifies the primary table for the annotated entity.
@Column specifies the mapped column for a persistent property or field.
@Id specifies the primary key of an entity.
@GeneratedValue provides for the specification of generation strategies for the values of primary keys. The GeneratedValue annotation may be applied to a primary key property or field of an entity or mapped superclass in conjunction with the Id annotation. The use of the GeneratedValue annotation is only required to be supported for simple primary keys. Use of the GeneratedValue annotation is not supported for derived primary keys.

In the model data class Customer, we defines 2 constructors:
– The default constructor protected Customer() {} is used only by Spring JPA and we will not directly to use it so we define the constructor with protected
– With the second constructor public Customer(String firstname, String lastname, int age), we use to create a Customer instance, so we define it with all properties of Customer class as parameters.

We also create a toString method that is used to print all property values of a customer instance on console for checking.

Create Spring JPA Repository to do CRUD operations

For easy to manipulate data with PostgreSQL, Spring JPA provides interface APIs to do the works. Here is the hierarchy structure of Spring JPA Repository:

Spring JPA CRUD Repository Hierarchy

Repository is central repository marker interface. Captures the domain type to manage as well as the domain type’s id type. General purpose is to hold type information as well as being able to discover interfaces that extend this one during classpath scanning for easy Spring bean creation.

Domain repositories extending this interface can selectively expose CRUD methods by simply declaring methods of the same signature as those declared in CrudRepository.

public interface Repository {

CrudRepository interface is used for generic CRUD operations on a repository for a specific type.

public interface CrudRepository extends Repository {

List APIs of CrudRepository as below:

All APIs of Spring JPA CrudRepository Interface
All APIs of Spring Jpa CrudRepository Interface

Details some APIs methods of Spring JPA CrudRepository:

  • S save(S entity) is used to save a given entity. Use the returned instance for further operations as the save operation might have changed the entity instance completely.
  • saveAll(Iterableentities) is used to save all given entities.
  • Optional findById(ID id) is used to retrieve an entity by its id
  • Iterable findAll() is used to return all instances of the type.
  • long count() is used to return the number of entities available
  • void deleteById(ID id) is used to deletes the entity with the given id.
  • void delete(T entity) is used to delete a given entity.
  • void deleteAll(Iterable entities) is used to delete the given entities.
  • void deleteAll() is used to delete all entities managed by the repository.

PagingAndSortingRepository is extension of CrudRepository to provide additional methods to retrieve entities using the pagination and sorting abstraction.

public interface PagingAndSortingRepository extends CrudRepository {...}

Here is a list APIs of Spring JPA PagingAndSortingRepository:

All APIs of Spring JPA PagingAndSortingRepository
All APIs of Spring JPA PagingAndSortingRepository
  • Iterable findAll(Sort sort) is used to return all entities sorted by the given options.
  • Page findAll(Pageable pageable) is used to return a Page of entities meeting the paging restriction provided in the Pageable object.

JpaRepository is a JPA specific extension of

public interface JpaRepository extends PagingAndSortingRepository, QueryByExampleExecutor {...}

Here is the list APIs of Spring JpaRepository:

The List APIs of JpaRepository
The List APIs of JpaRepository

Details of API methods of Spring JpaRepository:

  • S S saveAndFlush(S entity) is used to save an entity and flushes changes instantly
  • void deleteInBatch(Iterable entities) is used to deletes the given entities in a batch which means it will create a single Query. Assume that we will clear the javax.persistence.EntityManager after the call.
  • void deleteAllInBatch() is used to deletes all entities in a batch call.
The List APIs of JpaRepository
The List APIs of JpaRepository

In the tutorial, we just use CrudRepository to do the CRUD operations with PostgreSQL database:

package com.loizenjava.postgresqlspringboot.repository;

import java.util.List;


import com.loizenjava.postgresqlspringboot.model.Customer;

public interface CustomerRepository extends CrudRepository{
	List findByFirstname(String firstname);

List findByFirstname(String firstname) is an new API (be defined by developer) to find a customer entity in PostgreSQL table by the firstname field.

Implement CommandLineRunner to apply Spring Jpa CrudRepository to manipulate data in PostgreSQL

CommandLineRunner is used to indicate that a bean should run when it is contained within a SpringApplication. Multiple CommandLineRunner beans can be defined within the same application context and can be ordered using the Ordered interface or @Order annotation.

In the main class of SpringBoot application, we implement a CommandLineRunner and autowired the CustomerRepository to do CRUD operations: save, retrieve, update or delete entities in PostgreSQL database:

package com.loizenjava.postgresqlspringboot;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.loizenjava.postgresqlspringboot.model.Customer;
import com.loizenjava.postgresqlspringboot.repository.CustomerRepository;

public class SpringBootPostgreSqlApplication implements CommandLineRunner{
	CustomerRepository repository;
	public static void main(String[] args) {, args);

	public void run(String... args) throws Exception {
		// just save a Customer Customer("Jack", "Smith", 29));
		// save a list of customers to PostgreSQL
		repository.saveAll(Arrays.asList(new Customer("Adam", "Johnson", 25), 
				new Customer("Kim", "Smith", 30),
				new Customer("David", "Williams", 23), 
				new Customer("Jack", "Davis", 27)));
		// find all customers;
		Iterable lstCst = repository.findAll();
		// find all customers with firstname = Jack
		List jacks = repository.findByFirstname("Jack");
		// find a Customer by ID
		Optional cstOpt = repository.findById(2L);
		if(cstOpt.isPresent()) {
			Customer cst = cstOpt.get();
			// update the customer's firstname;
			cst.setFirstname("UPDATED FIRSTNAME");;
		// delete a Customer by ID

– In above segment code, we do following tasks:

  • Just save a customer entity: Customer("Jack", "Smith", 29))
  • Save a list of customer entities to PostgreSQL:
    repository.saveAll(Arrays.asList(new Customer("Adam", "Johnson", 25), ...
  • Retrieve all customer entities in PostgreSQL table:
    Iterable lstCst = repository.findAll()
  • Find all customer entities with firstname = Jack:
    List jacks = repository.findByFirstname("Jack")
  • Retrieve a customer entity by ID
    Optional cstOpt = repository.findById(2L)
  • Update the customer’s firstname:
    cst.setFirstname("UPDATED FIRSTNAME");;
  • Delete a customer entity by ID

Run SpringBoot Application and Check Results

Run above SpringBoot application, then check the PostgreSQL database, we see a created customer table:

results in postgresql customer table
results in postgresql customer table


Github updated later

Thanks for reading! See you later!

4 thoughts on “How to integrate SpringBoot 2.x with PostgreSQL database using Spring JPA”

  1. Your style is unique in comparison to other folks I’ve read stuff from.
    Thanks for posting when you have the opportunity, Guess I’ll
    just bookmark this page.

Leave a Reply

Your email address will not be published. Required fields are marked *