SlideShare a Scribd company logo
1 of 17
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

What's hot

Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring BootTrey Howard
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introductionRasheed Waraich
 
White paper mbre_en
White paper mbre_enWhite paper mbre_en
White paper mbre_enVisioneerUG
 
JavaDo#09 Spring boot入門ハンズオン
JavaDo#09 Spring boot入門ハンズオンJavaDo#09 Spring boot入門ハンズオン
JavaDo#09 Spring boot入門ハンズオンharuki ueno
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with SpringJoshua Long
 
Spring boot入門ハンズオン第二回
Spring boot入門ハンズオン第二回Spring boot入門ハンズオン第二回
Spring boot入門ハンズオン第二回haruki ueno
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!Jakub Kubrynski
 
Building a Spring Boot Application - Ask the Audience!
Building a Spring Boot Application - Ask the Audience!Building a Spring Boot Application - Ask the Audience!
Building a Spring Boot Application - Ask the Audience!🎤 Hanno Embregts 🎸
 
Analytics work space manager installation
Analytics work space manager installationAnalytics work space manager installation
Analytics work space manager installationRavi Kumar Lanke
 
Spring Boot & Actuators
Spring Boot & ActuatorsSpring Boot & Actuators
Spring Boot & ActuatorsVMware Tanzu
 
Spring Boot Workshop - January w/ Women Who Code
Spring Boot Workshop - January w/ Women Who CodeSpring Boot Workshop - January w/ Women Who Code
Spring Boot Workshop - January w/ Women Who CodePurnima Kamath
 
Enterprise Build And Test In The Cloud
Enterprise Build And Test In The CloudEnterprise Build And Test In The Cloud
Enterprise Build And Test In The CloudCarlos Sanchez
 
Enterprise Build And Test In The Cloud
Enterprise Build And Test In The CloudEnterprise Build And Test In The Cloud
Enterprise Build And Test In The CloudCarlos Sanchez
 

What's hot (20)

Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
White paper mbre_en
White paper mbre_enWhite paper mbre_en
White paper mbre_en
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Boot Intro
Spring Boot IntroSpring Boot Intro
Spring Boot Intro
 
JavaDo#09 Spring boot入門ハンズオン
JavaDo#09 Spring boot入門ハンズオンJavaDo#09 Spring boot入門ハンズオン
JavaDo#09 Spring boot入門ハンズオン
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Spring boot入門ハンズオン第二回
Spring boot入門ハンズオン第二回Spring boot入門ハンズオン第二回
Spring boot入門ハンズオン第二回
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Glassfish JEE Server Administration - Clustering
Glassfish JEE Server Administration - ClusteringGlassfish JEE Server Administration - Clustering
Glassfish JEE Server Administration - Clustering
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Building a Spring Boot Application - Ask the Audience!
Building a Spring Boot Application - Ask the Audience!Building a Spring Boot Application - Ask the Audience!
Building a Spring Boot Application - Ask the Audience!
 
Grails with swagger
Grails with swaggerGrails with swagger
Grails with swagger
 
Analytics work space manager installation
Analytics work space manager installationAnalytics work space manager installation
Analytics work space manager installation
 
Ready! Steady! SpringBoot!
Ready! Steady! SpringBoot! Ready! Steady! SpringBoot!
Ready! Steady! SpringBoot!
 
Spring Boot & Actuators
Spring Boot & ActuatorsSpring Boot & Actuators
Spring Boot & Actuators
 
Spring Boot Workshop - January w/ Women Who Code
Spring Boot Workshop - January w/ Women Who CodeSpring Boot Workshop - January w/ Women Who Code
Spring Boot Workshop - January w/ Women Who Code
 
Enterprise Build And Test In The Cloud
Enterprise Build And Test In The CloudEnterprise Build And Test In The Cloud
Enterprise Build And Test In The Cloud
 
Enterprise Build And Test In The Cloud
Enterprise Build And Test In The CloudEnterprise Build And Test In The Cloud
Enterprise Build And Test In The Cloud
 

Similar to Springboot2 postgresql-jpa-hibernate-crud-example

Spring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsSpring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsmichaelaaron25322
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introductionJonathan Holloway
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSUFYAN SATTAR
 
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfdokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfAppster1
 
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfdokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfAppster1
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Gunith Devasurendra
 
CollabSphere 2021 - DEV114 - The Nuts and Bolts of CI/CD With a Large XPages ...
CollabSphere 2021 - DEV114 - The Nuts and Bolts of CI/CD With a Large XPages ...CollabSphere 2021 - DEV114 - The Nuts and Bolts of CI/CD With a Large XPages ...
CollabSphere 2021 - DEV114 - The Nuts and Bolts of CI/CD With a Large XPages ...Jesse Gallagher
 
Spring Boot Whirlwind Tour
Spring Boot Whirlwind TourSpring Boot Whirlwind Tour
Spring Boot Whirlwind TourVMware Tanzu
 
Meetup 2022 - APIs with Quarkus.pdf
Meetup 2022 - APIs with Quarkus.pdfMeetup 2022 - APIs with Quarkus.pdf
Meetup 2022 - APIs with Quarkus.pdfRed Hat
 
Talk 1: Google App Engine Development: Java, Data Models, and other things yo...
Talk 1: Google App Engine Development: Java, Data Models, and other things yo...Talk 1: Google App Engine Development: Java, Data Models, and other things yo...
Talk 1: Google App Engine Development: Java, Data Models, and other things yo...Singapore Google Technology User Group
 
Spring5 New Features
Spring5 New FeaturesSpring5 New Features
Spring5 New FeaturesJay Lee
 
Configuring jpa in a Spring application
Configuring jpa in a  Spring applicationConfiguring jpa in a  Spring application
Configuring jpa in a Spring applicationJayasree Perilakkalam
 
dokumen.tips_introduction-to-spring-boot-58bb649a21ce5.pptx
dokumen.tips_introduction-to-spring-boot-58bb649a21ce5.pptxdokumen.tips_introduction-to-spring-boot-58bb649a21ce5.pptx
dokumen.tips_introduction-to-spring-boot-58bb649a21ce5.pptxAppster1
 
Vigneshram murugan cloud project_documentation
Vigneshram murugan cloud project_documentationVigneshram murugan cloud project_documentation
Vigneshram murugan cloud project_documentationVigneshram Murugan
 

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

Spring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsSpring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applications
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptx
 
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfdokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
 
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfdokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
 
CollabSphere 2021 - DEV114 - The Nuts and Bolts of CI/CD With a Large XPages ...
CollabSphere 2021 - DEV114 - The Nuts and Bolts of CI/CD With a Large XPages ...CollabSphere 2021 - DEV114 - The Nuts and Bolts of CI/CD With a Large XPages ...
CollabSphere 2021 - DEV114 - The Nuts and Bolts of CI/CD With a Large XPages ...
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Boot Whirlwind Tour
Spring Boot Whirlwind TourSpring Boot Whirlwind Tour
Spring Boot Whirlwind Tour
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
Meetup 2022 - APIs with Quarkus.pdf
Meetup 2022 - APIs with Quarkus.pdfMeetup 2022 - APIs with Quarkus.pdf
Meetup 2022 - APIs with Quarkus.pdf
 
Talk 1: Google App Engine Development: Java, Data Models, and other things yo...
Talk 1: Google App Engine Development: Java, Data Models, and other things yo...Talk 1: Google App Engine Development: Java, Data Models, and other things yo...
Talk 1: Google App Engine Development: Java, Data Models, and other things yo...
 
Spring5 New Features
Spring5 New FeaturesSpring5 New Features
Spring5 New Features
 
Configuring jpa in a Spring application
Configuring jpa in a  Spring applicationConfiguring jpa in a  Spring application
Configuring jpa in a Spring application
 
dokumen.tips_introduction-to-spring-boot-58bb649a21ce5.pptx
dokumen.tips_introduction-to-spring-boot-58bb649a21ce5.pptxdokumen.tips_introduction-to-spring-boot-58bb649a21ce5.pptx
dokumen.tips_introduction-to-spring-boot-58bb649a21ce5.pptx
 
Hibernate notes
Hibernate notesHibernate notes
Hibernate notes
 
Vigneshram murugan cloud project_documentation
Vigneshram murugan cloud project_documentationVigneshram murugan cloud project_documentation
Vigneshram murugan cloud project_documentation
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
PHP
PHP PHP
PHP
 

Recently uploaded

VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfRagavanV2
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...tanu pandey
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...SUHANI PANDEY
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086anil_gaur
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoordharasingh5698
 

Recently uploaded (20)

VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 

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