How to use Spring JPA with PostgreSQL | Spring Boot


In tradition approach, implementing Data Access Layer makes lots of boilerplate code. Spring JPA is a part of Spring Data, helps us improve our codes and reduce efforts for development and maintenance. Spring JPA supports us the ways to write interface for repositories and custom finder methods, the implementation will be done automatically by Spring Framework.

The tutorial shows you how to use Spring JPA with PostgreSQL using Spring Boot.

Related Posts:
How to use Spring JPA MySQL | Spring Boot
Spring JPA + PostgreSQL + AngularJS example | Spring Boot
Angular 4 + Spring JPA + PostgreSQL example | Angular 4 Http Client – Spring Boot RestApi Server
React Redux + Spring Boot + PostgreSQL CRUD example
Spring Boot + Angular 6 example | Spring Data JPA + REST + PostgreSQL CRUD example

I. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: RELEASE

II. Overview
1. Goal


2. Project Structure

– Class Customer corresponds to entity and table customer, it should be implemented Serializable.
CustomerRepository is an interface extends CrudRepository, will be autowired in WebController for implementing repository methods and custom finder methods.
WebController is a REST Controller which has request mapping methods for RESTful requests such as: save. findall, findbyid, findbylastname.
– Configuration for Spring Datasource and Spring JPA properties in
Dependencies for Spring Boot and PostgreSQL in pom.xml

3. Step to do

– Create Spring Boot project & add Dependencies
– Configure Spring JPA
– Create DataModel Class
– Create Spring JPA Repository Interface
– Create Web Controller
– Using CommandLineRunner to clear old data
– Create PostGreSQL table
– Run Spring Boot Application & Enjoy Result

4. Demo Video

III. Practice
1. Create Spring Boot project & add Dependencies

Open Spring Tool Suite, on Menu, choose File -> New -> Spring Starter Project, then fill each fields:
Click Next, in SQL: choose JPA and PostgreSQL, in Web: choose Web.
Click Finish, then our project will be created successfully.

Open pom.xml and check Dependencies:




These dependencies were auto-generated by the configuration we have done before.

2. Configure Spring JPA


3. Create DataModel Class

Under package model, create class Customer.

Content of

@Table(name = "customer")
public class Customer implements Serializable {

	private static final long serialVersionUID = -3009157732242241606L;
	@GeneratedValue(strategy = GenerationType.AUTO)
	private long id;

	@Column(name = "firstname")
	private String firstName;

	@Column(name = "lastname")
	private String lastName;

	protected Customer() {

	public Customer(String firstName, String lastName) {
		this.firstName = firstName;
		this.lastName = lastName;

	public String toString() {
		return String.format("Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName);

Annotation @Entity indicates that Customer is an Entity and @Table specifies the primary table (name customer) for the annotated @Entity.

@ID specifies the primary key and @GeneratedValue indicates generation strategy for value of primary key.

@Column: mapped column (in the table) for persistent fields (in Java class).

We have 2 constructor methods:
protected constructor will be used by Spring JPA.
public constructor is for creating instances.

4. Create Spring JPA Repository Interface

This interface helps us do all CRUD functions for class Customer.

public interface CustomerRepository extends CrudRepository{
	List findByLastName(String lastName);
5. Create Web Controller

The controller receives requests from client, using repository to update/get data and return results.

Content of

package com.springjpa.controller;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.springjpa.model.Customer;
import com.springjpa.repo.CustomerRepository;

public class WebController {
	CustomerRepository repository;
	public String process(){
		// save a single Customer Customer("Jack", "Smith"));
		// save a list of Customers Customer("Adam", "Johnson"), new Customer("Kim", "Smith"),
										new Customer("David", "Williams"), new Customer("Peter", "Davis")));
		return "Done";
	public String findAll(){
		String result = "";
		for(Customer cust : repository.findAll()){
			result += cust.toString() + "
"; } return result; } @RequestMapping("/findbyid") public String findById(@RequestParam("id") long id){ String result = ""; result = repository.findOne(id).toString(); return result; } @RequestMapping("/findbylastname") public String fetchDataByLastName(@RequestParam("lastname") String lastName){ String result = ""; for(Customer cust: repository.findByLastName(lastName)){ result += cust.toString() + "
"; } return result; } }

In the web controller methods which are annotated by @RequestMapping, we have used some methods of autowired repository which are implemented interface CrudRepository:

 S save(S entity); //for @RequestMapping("/save")
T findOne(ID id); //for @RequestMapping("/findbyid")
Iterable findAll(); //for @RequestMapping("/findall")

and the method findByLastName that we create in our interface CustomerRepository.

List findByLastName(String lastName);
6. Using CommandLineRunner to clear old data

In main class, implement CommandLineRunner to clear old data if existed:

package com.springjpa;

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.springjpa.repo.CustomerRepository;

public class SpringJpaPostgreSqlApplication implements CommandLineRunner{

	CustomerRepository repository;
	public static void main(String[] args){, args);

	public void run(String... arg0) throws Exception {
		// clear all record if existed before do the tutorial with new data 

7. Create PostGreSQL table

Open pdAdmin III, use SQL Editor and make a query to create customer table:

CREATE TABLE customer(
    firstname VARCHAR(20),
    lastname VARCHAR(20)


8. Run Spring Boot Application & Enjoy Result

– Config maven build:
clean install
– Run project with mode Spring Boot App
– Check results:

Request 1
The browser returns Done and if checking database testdb with table customer, we can see some data rows has been added:

Request 2

Request 3

Request 4

IV. Source Code


By grokonez | September 2, 2016.

Last updated on April 10, 2020.

Related Posts

26 thoughts on “How to use Spring JPA with PostgreSQL | Spring Boot”

  1. Im getting this error for /findbylastname and /findbyid

    There was an unexpected error (type=Bad Request, status=400).
    Required long parameter ‘id’ is not present

    Any thoughts why I’m getting this error?

    thank you!

    1. Hi Katrina,

      You should provide parameters in the Urls: findbyid?id=6 and findbylastname?lastname=Smith.
      /findbylastname or /findbyid is not enough.

      Best Regards.

    2. Hi,
      You’re getting this error since there is no record by the id 6. There are only 5 records with ids upto 5. Hence the query is run on a record that doesn’t exist.
      Try changing the ID localhost url to query any record with an ID from 1-5 and you’ll get the output as expected.


      You get the idea.

      Hope this was helpful!

    3. Any way to change the packaging as war and deploy on a server? If i do and deploy it deploys but keep getting 404s

  2. @Autowired CustomerRepository not working.
    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.springboot.repo.CustomerRepository]

    1. Maybe the Maven repository is out of date, So I had changed the version
      of SpringBoot from of 1.4 to RELEASE for supporting your case. You can download sourcecode & check again!

      Best Regards!

    2. make sure that springStart in the level before your entity in packages beacuse it scann all the inner packages for entities

  3. Hi. I can’t make it’s work.
    when I tried to build, I received an error:
    Tests in error:
    SpringJpaPostgreSqlApplicationTests.contextLoads » IllegalState Failed to load…

    1. Hi Juliana,

      Please check if you have add these lines of code to and have relative PostgreSQL database:


      Best Regards,

  4. Hi!
    Great tutorial! Unfortunately I can’t seem to get it to work. I get this error:
    2017-06-20 11:16:52.465 WARN 39054 — [ restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration’: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘javax.sql.DataSource’ available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

    1. Hi,

      From the exception, I see you have wrong configuration with DataSource.
      Please follow step by step guide in video to resolve it!


  5. hi, i got some error

    “Whitelabel Error Page

    This application has no explicit mapping for /error, so you are seeing this as a fallback.

    Mon Nov 06 11:06:07 WIB 2017
    There was an unexpected error (type=Not Found, status=404).
    No message available”

    whats wrong sir?

    1. Hello Alvin,

      We see that your problem comes from Interal Server Exception. Please double-check your implementation again with our article.
      We have double-checked our sourcecode and it works well!
      And also update some new code for cleaner and clearer view!

      Please check out and try it!


  6. Downloaded your code and tried to run it. It wont run.
    I am getting following error:

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springJpaPostgreSqlApplication': Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect bean class [com.springjpa.SpringJpaPostgreSqlApplication$$EnhancerBySpringCGLIB$$56221f41] for persistence metadata: could not find class that it depends on
    	at ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    	at ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    	at$1.getObject( ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    	at ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    	at ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    	at ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    	at ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    	at ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    	at ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    	at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh( ~[spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    	at org.springframework.boot.SpringApplication.refresh( [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    	at org.springframework.boot.SpringApplication.refreshContext( [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    	at [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    	at [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    	at [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    	at com.springjpa.SpringJpaPostgreSqlApplication.main( [classes/:na]
    Caused by: java.lang.IllegalStateException: Failed to introspect bean class [com.springjpa.SpringJpaPostgreSqlApplication$$EnhancerBySpringCGLIB$$56221f41] for persistence metadata: could not find class that it depends on
    	at ~[spring-orm-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    	at ~[spring-orm-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    	at ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    	at ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    	... 15 common frames omitted
    Caused by: java.lang.NoClassDefFoundError: org/springframework/data/repository/CrudRepository
    	at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.8.0_151]
    	at java.lang.ClassLoader.defineClass( ~[na:1.8.0_151]
    	at ~[na:1.8.0_151]
    	at ~[na:1.8.0_151]
    	at$100( ~[na:1.8.0_151]
    	at$ ~[na:1.8.0_151]
    	at$ ~[na:1.8.0_151]
    	at Method) ~[na:1.8.0_151]
    	at ~[na:1.8.0_151]
    	at java.lang.ClassLoader.loadClass( ~[na:1.8.0_151]
    	at sun.misc.Launcher$AppClassLoader.loadClass( ~[na:1.8.0_151]
    	at java.lang.ClassLoader.loadClass( ~[na:1.8.0_151]
    	at java.lang.Class.getDeclaredFields0(Native Method) ~[na:1.8.0_151]
    	at java.lang.Class.privateGetDeclaredFields( ~[na:1.8.0_151]
    	at java.lang.Class.getDeclaredFields( ~[na:1.8.0_151]
    	at org.springframework.util.ReflectionUtils.getDeclaredFields( ~[spring-core-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    	at org.springframework.util.ReflectionUtils.doWithLocalFields( ~[spring-core-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    	at ~[spring-orm-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    	at ~[spring-orm-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    	... 18 common frames omitted
    Caused by: java.lang.ClassNotFoundException:
    	at ~[na:1.8.0_151]
    	at java.lang.ClassLoader.loadClass( ~[na:1.8.0_151]
    	at sun.misc.Launcher$AppClassLoader.loadClass( ~[na:1.8.0_151]
    	at java.lang.ClassLoader.loadClass( ~[na:1.8.0_151]
    	... 37 common frames omitted
    1. Hello,

      Caused by:

      Caused by: java.lang.ClassNotFoundException:
      	at ~[na:1.8.0_151]
      	at java.lang.ClassLoader.loadClass( ~[na:1.8.0_151]
      	at sun.misc.Launcher$AppClassLoader.loadClass( ~[na:1.8.0_151]
      	at java.lang.ClassLoader.loadClass( ~[na:1.8.0_151]

      Please double check Spring JPA in your maven repository.
      Refer video guide for setup the project at:


  7. Hi,
    Thanks for the tutorial.

    Shouldn’t be repository.saveAll(List…) ?

    best regards.

  8. Hello, nice tutorial.

    A correction: on the controller code to save the list of customers you should use repository.saveAll instead of

    repository.saveAll(Arrays.asList(new Customer("Adam", "Johnson"), new Customer("Kim", "Smith")));
  9. How to ignore ERROR: duplicate key value violates unique constraint “customer_pkey” in this Application and proceed.
    I added one more save statement with same values and update the table to have first name and last name as primary key. Customer(“Jack”, “Smith”)); Customer(“Jack”, “Smith”));

    My own application has lot of duplicate data, I want to ignore all that and proceed with other data.
    Any idea how to handle the same in this tutorial

  10. I haven’t understand the properties on the PGAdmin side. My Pgadmin works at this URL;

    How should I give spring.datasource.url property ?
    And where can I get the spring.datasource.username and spring.datasource.password properties in the PgAdmin window?


  11. After running the /save , i am getting Done but my table is not getting updated with the data. Please let me know.

Got Something To Say:

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