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
How to use Spring JPA MariaDB | Spring Boot
Angular 4 + Spring JPA + PostgreSQL example | Angular 4 Http Client – Spring Boot RestApi Server

How to do this with Kotlin: Spring JPA + Postgresql | Spring Boot 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

springjpa-postgresql-thegoal

2. Project Structure

springjpa-postgresql-projectstructure
– 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 application.properties
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:
springjpa-postgresql-startproject
Click Next, in SQL: choose JPA and PostgreSQL, in Web: choose Web.
springjpa-postgresql-configdependencystarter
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

Open application.properties

3. Create DataModel Class

Under package model, create class Customer.

Content of Customer.java:

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.

5. Create Web Controller

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

Content of WebController.java

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

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

6. Using CommandLineRunner to clear old data

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

7. Create PostGreSQL table

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

springjpa-postgresql-createtable

8. Run Spring Boot Application & Enjoy Result

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

Request 1
http://localhost:8080/save
The browser returns Done and if checking database testdb with table customer, we can see some data rows has been added:
springjpa-postgresql-dbheck

Request 2
http://localhost:8080/findall
springjpa-postgresql--find-all

Request 3
http://localhost:8080/findbyid?id=6
springjpa-postgresql-findbyid6

Request 4
http://localhost:8080/findbylastname?lastname=Smith
springjpa-postgresql--findbylastnameSmith

IV. Source Code

SpringJPA-PostgreSQL

By JavaSampleApproach | September 2, 2016.

Last updated on November 6, 2017.


Related Posts


18 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.

      Example:
      http://localhost:8080/findbyid?id=5
      or
      http://localhost:8080/findbyid?id=4
      or
      http://localhost:8080/findbyid?id=3

      You get the idea.

      Hope this was helpful!

  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!

  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 application.properties 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!

      Regards,

  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?
    thanks

    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!

      Regards,
      JSA

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

    1. Hello,

      Cause by:

      Please double check Spring JPA in your maven repository.
      Refer video guide for setup the project at: https://youtu.be/ZURZMrfGsOA

      Regards,
      JSA

Got Something To Say:

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

*