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 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:
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:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> |
These dependencies were auto-generated by the configuration we have done before.
2. Configure Spring JPA
Open application.properties
spring.datasource.url=jdbc:postgresql://localhost/testdb spring.datasource.username=postgres spring.datasource.password=123 spring.jpa.generate-ddl=true |
3. Create DataModel Class
Under package model, create class Customer.
Content of Customer.java:
@Entity @Table(name = "customer") public class Customer implements Serializable { private static final long serialVersionUID = -3009157732242241606L; @Id @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; } @Override 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<Customer, Long>{ List<Customer> findByLastName(String lastName); } |
5. Create Web Controller
The controller receives requests from client, using repository to update/get data and return results.
Content of WebController.java
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; @RestController public class WebController { @Autowired CustomerRepository repository; @RequestMapping("/save") public String process(){ // save a single Customer repository.save(new Customer("Jack", "Smith")); // save a list of Customers repository.save(Arrays.asList(new Customer("Adam", "Johnson"), new Customer("Kim", "Smith"), new Customer("David", "Williams"), new Customer("Peter", "Davis"))); return "Done"; } @RequestMapping("/findall") public String findAll(){ String result = ""; for(Customer cust : repository.findAll()){ result += cust.toString() + "<br>"; } 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() + "<br>"; } 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 extends T> S save(S entity); //for @RequestMapping("/save") T findOne(ID id); //for @RequestMapping("/findbyid") Iterable<T> findAll(); //for @RequestMapping("/findall") |
and the method findByLastName that we create in our interface CustomerRepository.
List<Customer> 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; @SpringBootApplication public class SpringJpaPostgreSqlApplication implements CommandLineRunner{ @Autowired CustomerRepository repository; public static void main(String[] args){ SpringApplication.run(SpringJpaPostgreSqlApplication.class, args); } @Override public void run(String... arg0) throws Exception { // clear all record if existed before do the tutorial with new data repository.deleteAll(); } } |
7. Create PostGreSQL table
Open pdAdmin III, use SQL Editor and make a query to create customer table:
CREATE TABLE customer( id BIGINT PRIMARY KEY NOT NULL, 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
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:
Request 2
http://localhost:8080/findall
Request 3
http://localhost:8080/findbyid?id=6
Request 4
http://localhost:8080/findbylastname?lastname=Smith
IV. Source Code
Last updated on March 15, 2019.
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!
Hi Katrina,
You should provide parameters in the Urls: findbyid?id=6 and findbylastname?lastname=Smith.
/findbylastname
or/findbyid
is not enough.Best Regards.
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!
Any way to change the packaging as war and deploy on a server? If i do and deploy it deploys but keep getting 404s
Hello,
Below post will help you to deploy war file for SpringBoot app:
https://grokonez.com/spring-framework/spring-boot/deploy-spring-boot-web-app-war-file-tomcat-server-maven-build
Regards,
JSA
@Autowired CustomerRepository not working.
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.springboot.repo.CustomerRepository]
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!
make sure that springStart in the level before your entity in packages beacuse it scann all the inner packages for entities
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…
Hi Juliana,
Please check if you have add these lines of code to application.properties and have relative PostgreSQL database:
Best Regards,
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: {}
Hi,
From the exception, I see you have wrong configuration with DataSource.
Please follow step by step guide in video to resolve it!
Regards,
Very cool, thank you very much!
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
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
Thank you!
Thanks for this great tutorial!
Downloaded your code and tried to run it. It wont run.
I am getting following error:
Hello,
Caused by:
Please double check Spring JPA in your maven repository.
Refer video guide for setup the project at: https://youtu.be/ZURZMrfGsOA
Regards,
JSA
Hi,
Thanks for the tutorial.
Shouldn’t repository.save(List..) be repository.saveAll(List…) ?
best regards.
Benjamin
Hello, nice tutorial.
A correction: on the controller code to save the list of customers you should use repository.saveAll instead of repository.save
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.
repository.save(new Customer(“Jack”, “Smith”));
repository.save(new 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
Thanks for the tutorial!
I created a version of this application, added another related entity (a “Department”), and included a bunch of psql commands (postgresql’s powerful interactive utility) in the readme.txt.
https://github.com/apostrophe/simple-postgresql-app
great tutorial!!
I haven’t understand the properties on the PGAdmin side. My Pgadmin works at this URL;
http://127.0.0.1:54468/browser/
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?
spring.datasource.url=jdbc:postgresql://localhost/testdb
spring.datasource.username=postgres
spring.datasource.password=123