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

More Related Content

PPTX
Springboot2 postgresql-jpa-hibernate-crud-example with test
PPTX
Spring boot for buidling microservices
PPTX
Introduction to Spring Boot
PDF
Spring Boot and Microservices
PPTX
How to customize Spring Boot?
PPTX
Spring boot Introduction
PPTX
Spring boot
PPTX
Spring Boot
Springboot2 postgresql-jpa-hibernate-crud-example with test
Spring boot for buidling microservices
Introduction to Spring Boot
Spring Boot and Microservices
How to customize Spring Boot?
Spring boot Introduction
Spring boot
Spring Boot

What's hot (20)

PDF
Introduction to Spring Boot
PDF
Spring boot introduction
PDF
White paper mbre_en
PDF
Spring boot
PDF
Spring Boot Intro
PDF
JavaDo#09 Spring boot入門ハンズオン
PDF
REST APIs with Spring
PDF
Spring boot入門ハンズオン第二回
PDF
Spring Boot
PPTX
Spring Boot and REST API
PDF
Glassfish JEE Server Administration - Clustering
PDF
Introduction to Spring Boot!
PDF
Building a Spring Boot Application - Ask the Audience!
PPTX
Grails with swagger
PDF
Analytics work space manager installation
PPTX
Ready! Steady! SpringBoot!
PDF
Spring Boot & Actuators
PDF
Spring Boot Workshop - January w/ Women Who Code
KEY
Enterprise Build And Test In The Cloud
KEY
Enterprise Build And Test In The Cloud
Introduction to Spring Boot
Spring boot introduction
White paper mbre_en
Spring boot
Spring Boot Intro
JavaDo#09 Spring boot入門ハンズオン
REST APIs with Spring
Spring boot入門ハンズオン第二回
Spring Boot
Spring Boot and REST API
Glassfish JEE Server Administration - Clustering
Introduction to Spring Boot!
Building a Spring Boot Application - Ask the Audience!
Grails with swagger
Analytics work space manager installation
Ready! Steady! SpringBoot!
Spring Boot & Actuators
Spring Boot Workshop - January w/ Women Who Code
Enterprise Build And Test In The Cloud
Enterprise Build And Test In The Cloud
Ad

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

PPTX
Spring data jpa are used to develop spring applications
PPTX
Spring boot - an introduction
PPTX
SpringBootCompleteBootcamp.pptx
PDF
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
PDF
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
PDF
Rediscovering Spring with Spring Boot(1)
PPTX
CollabSphere 2021 - DEV114 - The Nuts and Bolts of CI/CD With a Large XPages ...
PDF
Spring Boot
PPTX
PDF
Spring Boot Whirlwind Tour
PDF
Spring boot jpa
PDF
Meetup 2022 - APIs with Quarkus.pdf
PPT
Talk 1: Google App Engine Development: Java, Data Models, and other things yo...
PDF
Spring5 New Features
PPTX
Configuring jpa in a Spring application
PPTX
dokumen.tips_introduction-to-spring-boot-58bb649a21ce5.pptx
DOCX
Hibernate notes
PDF
Vigneshram murugan cloud project_documentation
PPTX
Introduction to spring boot
PDF
php-and-zend-framework-getting-started
Spring data jpa are used to develop spring applications
Spring boot - an introduction
SpringBootCompleteBootcamp.pptx
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
Rediscovering Spring with Spring Boot(1)
CollabSphere 2021 - DEV114 - The Nuts and Bolts of CI/CD With a Large XPages ...
Spring Boot
Spring Boot Whirlwind Tour
Spring boot jpa
Meetup 2022 - APIs with Quarkus.pdf
Talk 1: Google App Engine Development: Java, Data Models, and other things yo...
Spring5 New Features
Configuring jpa in a Spring application
dokumen.tips_introduction-to-spring-boot-58bb649a21ce5.pptx
Hibernate notes
Vigneshram murugan cloud project_documentation
Introduction to spring boot
php-and-zend-framework-getting-started
Ad

Recently uploaded (20)

PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
III.4.1.2_The_Space_Environment.p pdffdf
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
Construction Project Organization Group 2.pptx
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
PPT on Performance Review to get promotions
PPTX
Geodesy 1.pptx...............................................
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
web development for engineering and engineering
PPT
Project quality management in manufacturing
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PDF
composite construction of structures.pdf
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
Model Code of Practice - Construction Work - 21102022 .pdf
III.4.1.2_The_Space_Environment.p pdffdf
Automation-in-Manufacturing-Chapter-Introduction.pdf
Construction Project Organization Group 2.pptx
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPT on Performance Review to get promotions
Geodesy 1.pptx...............................................
Operating System & Kernel Study Guide-1 - converted.pdf
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Internet of Things (IOT) - A guide to understanding
UNIT 4 Total Quality Management .pptx
OOP with Java - Java Introduction (Basics)
web development for engineering and engineering
Project quality management in manufacturing
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
composite construction of structures.pdf
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026

Springboot2 postgresql-jpa-hibernate-crud-example

  • 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