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:
org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-web org.postgresql postgresql runtime
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{ 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 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() + "
"; } 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") IterablefindAll(); //for @RequestMapping("/findall")
and the method findByLastName that we create in our interface CustomerRepository.
ListfindByLastName(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