Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
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

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.