SlideShare a Scribd company logo
Spring Boot + Spring Data JPA +
PostgreSQL Example by Ramesh Fadatare
In this article, you’ll learn how to configure Spring Boot, Spring Data JPA to support a
PostgreSQL database.
원본: https://www.javaguides.net/2019/08/spring-boot-spring-data-jpa-postgresql-example.html
옮긴이: monad
copyright 2017. OpenPLC all rights reserved. 2
1 Technologies and Tools Used
Technologies and Tools Used
• Spring Boot - 2.2.7
• JDK - 1.8 or later
• Spring Framework - 5.2.6.RELEASE
• Hibernate - 5.4.15.Final
• JPA – (spring-boot-starter-data-jpa)
2.2.7.RELEASE
• Maven - 3.2+
• IDE - Eclipse or Spring Tool Suite (STS)
• PostgreSQL - 42.2.5
Once, all the details are entered, click on Generate Project button will generate a spring boot project and downloads it. Next,
Unzip the downloaded zip file and import into your favorite IDE as a maven project.
copyright 2017. OpenPLC all rights reserved. 3
2 Dependency
Add PostgreSQL Dependency
Provide PostgreSQL in your pom.xml file.
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
Add Spring Data JPA Dependency
It’s very easy to configure Spring Boot to use the PostgreSQL database.
We are using Spring Data JPA with default Hibernate implementation so
which will support out of the box to work with different database
vendor without changing underlying code.
Add Spring Data JPA dependency to pom.xml file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
copyright 2017. OpenPLC all rights reserved. 4
3 Configure PostgreSQL Database
Configure PostgreSQL Database
Let’s configure Spring Boot to use PostgreSQL as our database. We are simply adding PostgreSQL database URL, username, and password in the
src/main/resources/application.properties file.
#spring boot server port, default is 8080
server.port=8989
#datasource
spring.datasource.url=jdbc:postgresql://localhost:5432/hibernatedb
spring.datasource.username=postgres
spring.datasource.password=pa$$w0rd
spring.jpa.show-sql=true
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL95Dialect
# Hibernate ddl auto(create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=update
For this simple application, it is
necessary to download and install
PostgreSQL.
And create a database with name
‘hibernatdb’.
copyright 2017. OpenPLC all rights reserved. 5
4 What we’ll build
What we’ll build
We will build a CRUD Restful APIs for a Simple Employee Management System using Spring Boot2 JPA and PostgreSQL database. Following are
five REST APIs (Controller handler methods) are created for Employee resource.
copyright 2017. OpenPLC all rights reserved. 6
5 Packaging Structure
Packaging Structure
Following is the packaging structure of our Employee Management System.
copyright 2017. OpenPLC all rights reserved. 7
6 Create JPA Entity – Employee.java
Employee.java
copyright 2017. OpenPLC all rights reserved. 8
7 Create Spring Data Repository –
EmployeeRepository.java
EmployeeRepository.java
copyright 2017. OpenPLC all rights reserved. 9
8 Create Spring Rest Controller –
EmployeeController.java(1/2)
EmployeeController.java
copyright 2017. OpenPLC all rights reserved. 10
8 Create Spring Rest Controller –
EmployeeController.java(2/2)
EmployeeController.java
copyright 2017. OpenPLC all rights reserved. 11
ResourceNotFoundException.java
Let’s see what Spring Boot does when an exception is thrown from a
Resource. We can specify the Response Status for a specific exception
along with the definition of the Exception of ‘@ResponseStatus’
annotation.
9 What happens when we throw an Exception?
Exception(Error) Handling for RESTful Services
Spring Boot provides a good default implementation for exception
handling for RESTful Services. Let’s quickly look at the default Handling
features provided by Spring Boot.
Resource Not Present
Heres what happens when you fire a request to not resource found:
http://localhost:8989/some-dummy-url
That’s a cool error response. It contains all the details that are typically
needed.
copyright 2017. OpenPLC all rights reserved. 12
10 Customizing Error Response Structure –
ErrorDetails.java
Customize Error Response Structure
Default error response provided by Spring Boot contains all the details that are typically needed. However, you might want to create a framework
independent response structure for your organization. In that case, you can define a specific error response structure.
copyright 2017. OpenPLC all rights reserved. 13
11 ExceptionHandler for using ErrorDetails
Exception Handler for using ErrorDetails – GlobalExceptionHandler.java
To use ErrorDetails to return the error response. Let’s create a GlobalExceptionHandler class annotated with @ControllerAdvice annotation. This
class handles exception specific and global exception in a single place.
copyright 2017. OpenPLC all rights reserved. 14
12 SpringApplication.run()
SpringApplication.run()
1. Download and install PostgreSQL
2. Create Database - hibernatedb
copyright 2017. OpenPLC all rights reserved. 15
13 Run Application
Run Application
This spring boot application has an entry point Java class called Springboot2PostgresqlJpaHibernateCrudExampleApplication.java with the public
static void main(String[] args) method, which you can run to start the application.
@SpringBootApplication is a convenience annotation that adds all of the following:
• @Configuration tags the class as a source of bean definitions for the application context.
• @EnableAutoConfiguration tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.
• Normally you would add @EnableWebMvc for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the
classpath. This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.
• @ComponentScan tells Spring to look for other components, configurations, and services in the hello package, allowing it to find controllers.
copyright 2017. OpenPLC all rights reserved. 16
14 Test Application
pgAdmin4
POSTMAN
Choose raw and JSON
pgAdmin4
IDE console
copyright 2017. OpenPLC all rights reserved. 17
15 etc
A Warning was happened.
2020-05-19 15:01:19.571 WARN 37996 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view
is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure
spring.jpa.open-in-view to disable this warning
copyright 2017. OpenPLC all rights reserved. 18
16 CRUD REST APIs Integration Testing
Original URL: https://www.javaguides.net/2018/09/spring-boot-2-rest-apis-integration-testing.html
The spring-boot-starter-test “Starter” (in the test scope) contains the following provided libraries:
• JUnit: The de-facto standard for unit testing Java applications.
• Spring Test & Spring Boot Test: Utilities and integration test support for Spring Boot applications.
• AssertJ: A fluent assertion library.
• Hamcrest: A library of matcher objects (also known as constraints or predicates).
• Mockito: A Java mocking framework.
• JSONassert: An assertion library for JSON.
• JsonPath: XPath for JSON.
copyright 2017. OpenPLC all rights reserved. 19
17 Test Code (1/2)
SpringBootTest.WebEnvironment.RANDOM_PORT
While running the integration tests that start the embedded
servlet containers, it is better to use
WebEnvironment.RANDOM_PORT so that it won’t conflict with
other running applications, especially in Continuous
Integration(CI) environments where multiple builds run in parallel.
You can specify which configuration classes to use to build
ApplicationContext by using the classes attribute of
@SpringBootTest annotation.
The TestRestTemplate bean will be registered automatically only
when @SpringBootTest is started with an embedded servlet
container.
As you need to test REST endpoint, you start the embedded
servlet container by specifying the WebEnvironment attribute of
@SpringBootTest.
copyright 2017. OpenPLC all rights reserved. 20
17 Test Code (2/2)
WebEnvironment.MOCK
The default WebEnvironment value is WebEnvironment.MOCK,
which doesn’t start an embedded servlet container.
You can use various WebEnvironment values based on how you
want to runt the tests.
• MOCK(default) – Loads a WebApplicationContext and
provides a mock servlet environment. It will not start an
embedded servlet container. If servlet APIs are not on your
classpath, this mode will fall back to creating a regular non-
web-ApplicationContext.
• RANDOM_PORT – Loads a
ServletWebServerApplicationContext and starts an embedded
servlet container listening on a random available port.
• DEFINED_PORT – Loads a ServletWebServerApplicationContext
and starts an embedded servlet container listening on a
defined port(server.port).
• NONE – Loads an ApplicationContext using SpringApplication
but does not provide a servlet environment.

More Related Content

PPTX
Mongo db
PPTX
Springboot2 postgresql-jpa-hibernate-crud-example
PPTX
Introduction to Spring Boot
PPTX
Spring Boot
PPTX
How to customize Spring Boot?
PPTX
Spring boot Introduction
PPTX
Developing Agile Java Applications using Spring tools
PDF
Rediscovering Spring with Spring Boot(1)
Mongo db
Springboot2 postgresql-jpa-hibernate-crud-example
Introduction to Spring Boot
Spring Boot
How to customize Spring Boot?
Spring boot Introduction
Developing Agile Java Applications using Spring tools
Rediscovering Spring with Spring Boot(1)

What's hot (20)

PPTX
Spring boot for buidling microservices
PPTX
Spring boot
PDF
Introduction to Spring Boot
PPTX
Introduction to spring boot
PDF
Spring Boot and Microservices
PDF
Spring boot introduction
PDF
REST APIs with Spring
PDF
PUC SE Day 2019 - SpringBoot
PPTX
Spring boot - an introduction
PDF
Spring Boot
PDF
Glassfish JEE Server Administration - Clustering
ODP
Java 9 Features
PDF
Getting Reactive with Spring Framework 5.0’s GA release
PPTX
Spring boot 3g
PPTX
Spring boot
PDF
Spring boot
PDF
White paper mbre_en
PDF
Testing Spring Boot Applications
PPT
Springboot introduction
PPT
Spring Boot in Action
Spring boot for buidling microservices
Spring boot
Introduction to Spring Boot
Introduction to spring boot
Spring Boot and Microservices
Spring boot introduction
REST APIs with Spring
PUC SE Day 2019 - SpringBoot
Spring boot - an introduction
Spring Boot
Glassfish JEE Server Administration - Clustering
Java 9 Features
Getting Reactive with Spring Framework 5.0’s GA release
Spring boot 3g
Spring boot
Spring boot
White paper mbre_en
Testing Spring Boot Applications
Springboot introduction
Spring Boot in Action
Ad

Similar to Springboot2 postgresql-jpa-hibernate-crud-example with test (20)

PPTX
SpringBootCompleteBootcamp.pptx
PDF
Spring Boot: a Quick Introduction
PPTX
Leaner microservices with Java 10
PPTX
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
ODP
Xke spring boot
PDF
Spring Boot Interview Questions PDF By ScholarHat
PDF
Spring Boot
PPTX
dokumen.tips_introduction-to-spring-boot-58bb649a21ce5.pptx
PDF
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
PDF
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
PPTX
Spring data jpa are used to develop spring applications
PPTX
PPTX
Spring_Boot_Microservices-5_Day_Session.pptx
PPTX
Module 6 _ Spring Boot for java application to begin
PPTX
Introduction to Spring sec2.pptx
PPTX
Spring Test Framework
PPTX
Learn Spring Boot With Bisky - Intoduction
PPTX
Spring boot
PDF
Java SpringBoot Book Build+Your+API+with+Spring.pdf
PDF
Spring Boot Whirlwind Tour
SpringBootCompleteBootcamp.pptx
Spring Boot: a Quick Introduction
Leaner microservices with Java 10
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
Xke spring boot
Spring Boot Interview Questions PDF By ScholarHat
Spring Boot
dokumen.tips_introduction-to-spring-boot-58bb649a21ce5.pptx
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
Spring data jpa are used to develop spring applications
Spring_Boot_Microservices-5_Day_Session.pptx
Module 6 _ Spring Boot for java application to begin
Introduction to Spring sec2.pptx
Spring Test Framework
Learn Spring Boot With Bisky - Intoduction
Spring boot
Java SpringBoot Book Build+Your+API+with+Spring.pdf
Spring Boot Whirlwind Tour
Ad

Recently uploaded (20)

PPT
introduction to datamining and warehousing
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
DOCX
573137875-Attendance-Management-System-original
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
additive manufacturing of ss316l using mig welding
PDF
Digital Logic Computer Design lecture notes
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
Construction Project Organization Group 2.pptx
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
Sustainable Sites - Green Building Construction
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
composite construction of structures.pdf
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPTX
UNIT 4 Total Quality Management .pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
R24 SURVEYING LAB MANUAL for civil enggi
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
introduction to datamining and warehousing
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
573137875-Attendance-Management-System-original
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
additive manufacturing of ss316l using mig welding
Digital Logic Computer Design lecture notes
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Construction Project Organization Group 2.pptx
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Sustainable Sites - Green Building Construction
bas. eng. economics group 4 presentation 1.pptx
composite construction of structures.pdf
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
UNIT 4 Total Quality Management .pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
R24 SURVEYING LAB MANUAL for civil enggi
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx

Springboot2 postgresql-jpa-hibernate-crud-example with test

  • 1. Spring Boot + Spring Data JPA + PostgreSQL Example by Ramesh Fadatare In this article, you’ll learn how to configure Spring Boot, Spring Data JPA to support a PostgreSQL database. 원본: https://www.javaguides.net/2019/08/spring-boot-spring-data-jpa-postgresql-example.html 옮긴이: monad
  • 2. copyright 2017. OpenPLC all rights reserved. 2 1 Technologies and Tools Used Technologies and Tools Used • Spring Boot - 2.2.7 • JDK - 1.8 or later • Spring Framework - 5.2.6.RELEASE • Hibernate - 5.4.15.Final • JPA – (spring-boot-starter-data-jpa) 2.2.7.RELEASE • Maven - 3.2+ • IDE - Eclipse or Spring Tool Suite (STS) • PostgreSQL - 42.2.5 Once, all the details are entered, click on Generate Project button will generate a spring boot project and downloads it. Next, Unzip the downloaded zip file and import into your favorite IDE as a maven project.
  • 3. copyright 2017. OpenPLC all rights reserved. 3 2 Dependency Add PostgreSQL Dependency Provide PostgreSQL in your pom.xml file. <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> Add Spring Data JPA Dependency It’s very easy to configure Spring Boot to use the PostgreSQL database. We are using Spring Data JPA with default Hibernate implementation so which will support out of the box to work with different database vendor without changing underlying code. Add Spring Data JPA dependency to pom.xml file. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
  • 4. copyright 2017. OpenPLC all rights reserved. 4 3 Configure PostgreSQL Database Configure PostgreSQL Database Let’s configure Spring Boot to use PostgreSQL as our database. We are simply adding PostgreSQL database URL, username, and password in the src/main/resources/application.properties file. #spring boot server port, default is 8080 server.port=8989 #datasource spring.datasource.url=jdbc:postgresql://localhost:5432/hibernatedb spring.datasource.username=postgres spring.datasource.password=pa$$w0rd spring.jpa.show-sql=true ## Hibernate Properties # The SQL dialect makes Hibernate generate better SQL for the chosen database spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL95Dialect # Hibernate ddl auto(create, create-drop, validate, update) spring.jpa.hibernate.ddl-auto=update For this simple application, it is necessary to download and install PostgreSQL. And create a database with name ‘hibernatdb’.
  • 5. copyright 2017. OpenPLC all rights reserved. 5 4 What we’ll build What we’ll build We will build a CRUD Restful APIs for a Simple Employee Management System using Spring Boot2 JPA and PostgreSQL database. Following are five REST APIs (Controller handler methods) are created for Employee resource.
  • 6. copyright 2017. OpenPLC all rights reserved. 6 5 Packaging Structure Packaging Structure Following is the packaging structure of our Employee Management System.
  • 7. copyright 2017. OpenPLC all rights reserved. 7 6 Create JPA Entity – Employee.java Employee.java
  • 8. copyright 2017. OpenPLC all rights reserved. 8 7 Create Spring Data Repository – EmployeeRepository.java EmployeeRepository.java
  • 9. copyright 2017. OpenPLC all rights reserved. 9 8 Create Spring Rest Controller – EmployeeController.java(1/2) EmployeeController.java
  • 10. copyright 2017. OpenPLC all rights reserved. 10 8 Create Spring Rest Controller – EmployeeController.java(2/2) EmployeeController.java
  • 11. copyright 2017. OpenPLC all rights reserved. 11 ResourceNotFoundException.java Let’s see what Spring Boot does when an exception is thrown from a Resource. We can specify the Response Status for a specific exception along with the definition of the Exception of ‘@ResponseStatus’ annotation. 9 What happens when we throw an Exception? Exception(Error) Handling for RESTful Services Spring Boot provides a good default implementation for exception handling for RESTful Services. Let’s quickly look at the default Handling features provided by Spring Boot. Resource Not Present Heres what happens when you fire a request to not resource found: http://localhost:8989/some-dummy-url That’s a cool error response. It contains all the details that are typically needed.
  • 12. copyright 2017. OpenPLC all rights reserved. 12 10 Customizing Error Response Structure – ErrorDetails.java Customize Error Response Structure Default error response provided by Spring Boot contains all the details that are typically needed. However, you might want to create a framework independent response structure for your organization. In that case, you can define a specific error response structure.
  • 13. copyright 2017. OpenPLC all rights reserved. 13 11 ExceptionHandler for using ErrorDetails Exception Handler for using ErrorDetails – GlobalExceptionHandler.java To use ErrorDetails to return the error response. Let’s create a GlobalExceptionHandler class annotated with @ControllerAdvice annotation. This class handles exception specific and global exception in a single place.
  • 14. copyright 2017. OpenPLC all rights reserved. 14 12 SpringApplication.run() SpringApplication.run() 1. Download and install PostgreSQL 2. Create Database - hibernatedb
  • 15. copyright 2017. OpenPLC all rights reserved. 15 13 Run Application Run Application This spring boot application has an entry point Java class called Springboot2PostgresqlJpaHibernateCrudExampleApplication.java with the public static void main(String[] args) method, which you can run to start the application. @SpringBootApplication is a convenience annotation that adds all of the following: • @Configuration tags the class as a source of bean definitions for the application context. • @EnableAutoConfiguration tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. • Normally you would add @EnableWebMvc for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet. • @ComponentScan tells Spring to look for other components, configurations, and services in the hello package, allowing it to find controllers.
  • 16. copyright 2017. OpenPLC all rights reserved. 16 14 Test Application pgAdmin4 POSTMAN Choose raw and JSON pgAdmin4 IDE console
  • 17. copyright 2017. OpenPLC all rights reserved. 17 15 etc A Warning was happened. 2020-05-19 15:01:19.571 WARN 37996 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
  • 18. copyright 2017. OpenPLC all rights reserved. 18 16 CRUD REST APIs Integration Testing Original URL: https://www.javaguides.net/2018/09/spring-boot-2-rest-apis-integration-testing.html The spring-boot-starter-test “Starter” (in the test scope) contains the following provided libraries: • JUnit: The de-facto standard for unit testing Java applications. • Spring Test & Spring Boot Test: Utilities and integration test support for Spring Boot applications. • AssertJ: A fluent assertion library. • Hamcrest: A library of matcher objects (also known as constraints or predicates). • Mockito: A Java mocking framework. • JSONassert: An assertion library for JSON. • JsonPath: XPath for JSON.
  • 19. copyright 2017. OpenPLC all rights reserved. 19 17 Test Code (1/2) SpringBootTest.WebEnvironment.RANDOM_PORT While running the integration tests that start the embedded servlet containers, it is better to use WebEnvironment.RANDOM_PORT so that it won’t conflict with other running applications, especially in Continuous Integration(CI) environments where multiple builds run in parallel. You can specify which configuration classes to use to build ApplicationContext by using the classes attribute of @SpringBootTest annotation. The TestRestTemplate bean will be registered automatically only when @SpringBootTest is started with an embedded servlet container. As you need to test REST endpoint, you start the embedded servlet container by specifying the WebEnvironment attribute of @SpringBootTest.
  • 20. copyright 2017. OpenPLC all rights reserved. 20 17 Test Code (2/2) WebEnvironment.MOCK The default WebEnvironment value is WebEnvironment.MOCK, which doesn’t start an embedded servlet container. You can use various WebEnvironment values based on how you want to runt the tests. • MOCK(default) – Loads a WebApplicationContext and provides a mock servlet environment. It will not start an embedded servlet container. If servlet APIs are not on your classpath, this mode will fall back to creating a regular non- web-ApplicationContext. • RANDOM_PORT – Loads a ServletWebServerApplicationContext and starts an embedded servlet container listening on a random available port. • DEFINED_PORT – Loads a ServletWebServerApplicationContext and starts an embedded servlet container listening on a defined port(server.port). • NONE – Loads an ApplicationContext using SpringApplication but does not provide a servlet environment.