SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Downloaden Sie, um offline zu lesen
Curso Java COMPLETO
educandoweb.com
Dr. Nelio Alves
Projeto web services com Spring Boot e JPA / Hibernate
Objetivos
 Criar projeto Spring Boot Java
 Implementar modelo de domínio
 Estruturar camadas lógicas: resource, service, repository
 Configurar banco de dados de teste (H2)
 Povoar o banco de dados
 CRUD - Create, Retrieve, Update, Delete
 Tratamento de exceções
Github:
https://github.com/acenelio/workshop-springboot2-jpa
Domain Model
Domain Instance
Logical Layers
Project created
Checklist:
 File -> New -> Spring Starter Project
o Maven
o Java 11
o Packing JAR
o Dependencies: Spring Web Starter
User entity and resource
Basic entity checklist:
 Basic attributes
 Associations (instantiate collections)
 Constructors
 Getters & Setters (collections: only get)
 hashCode & equals
 Serializable
H2 database, test profile, JPA
Checklist:
 JPA & H2 dependencies
 application.properties
 application-test.properties
 Entity: JPA mapping
Dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
application.properties:
spring.profiles.active=test
spring.jpa.open-in-view=true
application-test.properties:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
JPA repository, dependency injection, database seeding
Checklist:
 UserRepository extends JPARepository<User, Long>
 Configuration class for "test" profile
 @Autowired UserRepository
 Instantiate objects in memory
 Persist objects
Objects:
User u1 = new User(null, "Maria Brown", "maria@gmail.com", "988888888", "123456");
User u2 = new User(null, "Alex Green", "alex@gmail.com", "977777777", "123456");
Service layer, component registration
Order, Instant, ISO 8601
Basic new entity checklist:
 Entity
o "To many" association, lazy loading, JsonIgnore
 Repository
 Seed
 Service
 Resource
Objects:
Order o1 = new Order(null, Instant.parse("2019-06-20T19:53:07Z"), u1);
Order o2 = new Order(null, Instant.parse("2019-07-21T03:42:10Z"), u2);
Order o3 = new Order(null, Instant.parse("2019-07-22T15:21:22Z"), u1);
OrderStatus enum
Category
Objects:
Category cat1 = new Category(null, "Electronics");
Category cat2 = new Category(null, "Books");
Category cat3 = new Category(null, "Computers");
Product
Objects:
Product p1 = new Product(null, "The Lord of the Rings", "Lorem ipsum dolor sit amet, consectetur.", 90.5, "");
Product p2 = new Product(null, "Smart TV", "Nulla eu imperdiet purus. Maecenas ante.", 2190.0, "");
Product p3 = new Product(null, "Macbook Pro", "Nam eleifend maximus tortor, at mollis.", 1250.0, "");
Product p4 = new Product(null, "PC Gamer", "Donec aliquet odio ac rhoncus cursus.", 1200.0, "");
Product p5 = new Product(null, "Rails for Dummies", "Cras fringilla convallis sem vel faucibus.", 100.99, "");
Many-to-many association with JoinTable
OrderItem, many-to-many association with extra attributes
Checklist:
 OrderItemPK
 OrderItem
 Order one-to-many association
 Seed
Objects:
OrderItem oi1 = new OrderItem(o1, p1, 2, p1.getPrice());
OrderItem oi2 = new OrderItem(o1, p3, 1, p3.getPrice());
OrderItem oi3 = new OrderItem(o2, p3, 2, p3.getPrice());
OrderItem oi4 = new OrderItem(o3, p5, 2, p5.getPrice());
Product-OrderItem one-to-many association
Payment, one-to-one association
Subtotal & Total methods
User insert
Checklist:
 UserService
 UserResource
Test:
{
"name": "Bob Brown",
"email": "bob@gmail.com",
"phone": "977557755",
"password": "123456"
}
User delete
Checklist:
 UserService
 UserResource
User update
Checklist:
 UserService
 UserResource
Test:
{
"name": "Bob Brown",
"email": "bob@gmail.com",
"phone": "977557755"
}
Exception handling - findById
Checklist:
 NEW CLASS: services.exceptions.ResourceNotFoundException
 NEW CLASS: resources.exceptions.StandardError
 NEW CLASS: resources.exceptions.ResourceExceptionHandler
 UserService
Exception handling - delete
Checklist:
 NEW CLASS: services.exceptions.DatabaseException
 ResourceExceptionHandler
 UserService
o EmptyResultDataAccessException
o DataIntegrityViolationException
Exception handling - update
Checklist:
 UserService
o EntityNotFoundException
Create Heroku app & provision PostgreSQL
Checklist:
 Heroku Sign Up
 Create app
 Provision PostgreSQL
o App dashboard -> Resources
o Search "postgres" -> select "Heroku Postgres"
Install local PostgreSQL
Checklist:
 Download and install: https://www.postgresql.org/download/
o Super user: postgres
o Password: 1234567
o Port: 5432
 Start/stop service: Task manager -> Services
 Check instalation
o Start pgAdmin
o Databases -> Create -> Database
 Encoding: UTF8
Dev profile
Checklist:
 PgAdmin: create local database: create database springboot_course
 Add PostgreSQL Maven dependency
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
 Create file: application-dev.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/springboot_course
spring.datasource.username=postgres
spring.datasource.password=1234567
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
jwt.secret=MYJWTSECRET
jwt.expiration=3600000
 Update application.properties: spring.profiles.active=dev
 Run application
Get SQL script from local PostgreSQL
 PgAdmin: get SQL script:
o Select database
o Tools -> Backup
 Format: Plain
 Encoding: UTF8
 Dump options:
 Only schema: YES
 Blobs: NO
 Do not save: (ALL)
 Verbose messages: NO
 Delete instructions before CREATE statements
Run SQL Script
Checklist:
 App dashboard -> Settings - > Config Vars
EXAMPLE:
postgres://wavglvupbdad:358f443aafe452eca4c58fbc15d02e50b08130c7aaea3aff6c4f59c
13f9abb@ec2-23-21-106-266.compute-1.amazonaws.com:5432/d7u9ub86cdsu
user: wavglvupbdad
password: 358f443aafe452eca4c58fbc15d02e50b08130c7aaea3aff6c4f59c13f9abb
server: ec2-23-21-106-266.compute-1.amazonaws.com
port: 5432
database: d7u9ub86cdsu
 PgAdmin: Servers -> Create -> Server
o Advanced -> DB rescriction: (database)
 Database -> Query Tool
o Load and run SQL Script
Deploy app to Heroku
 Heroku app dashboard -> Deploy
heroku git:remote -a myapp
git remote -v
 Setup Heroku app Config Vars
o DATABASE_URL
o JWT_EXPIRATION
o JWT_SECRET
 Create: application-prod.properties
spring.datasource.url=${DATABASE_URL}
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=false
jwt.secret=${JWT_SECRET}
jwt.expiration=${JWT_EXPIRATION}
 Update application.properties: spring.profiles.active=prod
 Create files: system.properties
java.runtime.version=11
 Send to Heroku:
git add .
git commit -m "Deploy app to Heroku"
git push heroku master

Weitere ähnliche Inhalte

Ähnlich wie Projeto-web-services-Spring-Boot-JPA.pdf

Vancouver presentation
Vancouver presentationVancouver presentation
Vancouver presentationColleen_Murphy
 
KubeCon EU 2016: Kubernetes and the Potential for Higher Level Interfaces
KubeCon EU 2016: Kubernetes and the Potential for Higher Level InterfacesKubeCon EU 2016: Kubernetes and the Potential for Higher Level Interfaces
KubeCon EU 2016: Kubernetes and the Potential for Higher Level InterfacesKubeAcademy
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know Norberto Leite
 
Mongo+java (1)
Mongo+java (1)Mongo+java (1)
Mongo+java (1)MongoDB
 
How Bitbucket Pipelines Loads Connect UI Assets Super-fast
How Bitbucket Pipelines Loads Connect UI Assets Super-fastHow Bitbucket Pipelines Loads Connect UI Assets Super-fast
How Bitbucket Pipelines Loads Connect UI Assets Super-fastAtlassian
 
REST with Eve and Python
REST with Eve and PythonREST with Eve and Python
REST with Eve and PythonPiXeL16
 
Infrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsInfrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsMykyta Protsenko
 
The Big Picture and How to Get Started
The Big Picture and How to Get StartedThe Big Picture and How to Get Started
The Big Picture and How to Get Startedguest1af57e
 
Prediction io 架構與整合 -DataCon.TW-2017
Prediction io 架構與整合 -DataCon.TW-2017Prediction io 架構與整合 -DataCon.TW-2017
Prediction io 架構與整合 -DataCon.TW-2017William Lee
 
Flask patterns
Flask patternsFlask patterns
Flask patternsit-people
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)Igor Bronovskyy
 
Saving Time And Effort With QuickBase Api - Sergio Haro
Saving Time And Effort With QuickBase Api - Sergio HaroSaving Time And Effort With QuickBase Api - Sergio Haro
Saving Time And Effort With QuickBase Api - Sergio HaroQuickBase, Inc.
 
Infrastructure = code - 1 year later
Infrastructure = code - 1 year laterInfrastructure = code - 1 year later
Infrastructure = code - 1 year laterChristian Ortner
 
Automatically Scaling Your Kubernetes Workloads - SVC209-S - Anaheim AWS Summit
Automatically Scaling Your Kubernetes Workloads - SVC209-S - Anaheim AWS SummitAutomatically Scaling Your Kubernetes Workloads - SVC209-S - Anaheim AWS Summit
Automatically Scaling Your Kubernetes Workloads - SVC209-S - Anaheim AWS SummitAmazon Web Services
 
Automating Front-End Workflow
Automating Front-End WorkflowAutomating Front-End Workflow
Automating Front-End WorkflowDimitris Tsironis
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php PresentationAlan Pinstein
 
Mastering Grails 3 Plugins - G3 Summit 2016
Mastering Grails 3 Plugins - G3 Summit 2016Mastering Grails 3 Plugins - G3 Summit 2016
Mastering Grails 3 Plugins - G3 Summit 2016Alvaro Sanchez-Mariscal
 

Ähnlich wie Projeto-web-services-Spring-Boot-JPA.pdf (20)

Vancouver presentation
Vancouver presentationVancouver presentation
Vancouver presentation
 
KubeCon EU 2016: Kubernetes and the Potential for Higher Level Interfaces
KubeCon EU 2016: Kubernetes and the Potential for Higher Level InterfacesKubeCon EU 2016: Kubernetes and the Potential for Higher Level Interfaces
KubeCon EU 2016: Kubernetes and the Potential for Higher Level Interfaces
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
Mongo+java (1)
Mongo+java (1)Mongo+java (1)
Mongo+java (1)
 
How Bitbucket Pipelines Loads Connect UI Assets Super-fast
How Bitbucket Pipelines Loads Connect UI Assets Super-fastHow Bitbucket Pipelines Loads Connect UI Assets Super-fast
How Bitbucket Pipelines Loads Connect UI Assets Super-fast
 
REST with Eve and Python
REST with Eve and PythonREST with Eve and Python
REST with Eve and Python
 
Infrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsInfrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and Ops
 
The Big Picture and How to Get Started
The Big Picture and How to Get StartedThe Big Picture and How to Get Started
The Big Picture and How to Get Started
 
Prediction io 架構與整合 -DataCon.TW-2017
Prediction io 架構與整合 -DataCon.TW-2017Prediction io 架構與整合 -DataCon.TW-2017
Prediction io 架構與整合 -DataCon.TW-2017
 
Serverless Java on Kubernetes
Serverless Java on KubernetesServerless Java on Kubernetes
Serverless Java on Kubernetes
 
GradleFX
GradleFXGradleFX
GradleFX
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
Saving Time And Effort With QuickBase Api - Sergio Haro
Saving Time And Effort With QuickBase Api - Sergio HaroSaving Time And Effort With QuickBase Api - Sergio Haro
Saving Time And Effort With QuickBase Api - Sergio Haro
 
Infrastructure = code - 1 year later
Infrastructure = code - 1 year laterInfrastructure = code - 1 year later
Infrastructure = code - 1 year later
 
Automatically Scaling Your Kubernetes Workloads - SVC209-S - Anaheim AWS Summit
Automatically Scaling Your Kubernetes Workloads - SVC209-S - Anaheim AWS SummitAutomatically Scaling Your Kubernetes Workloads - SVC209-S - Anaheim AWS Summit
Automatically Scaling Your Kubernetes Workloads - SVC209-S - Anaheim AWS Summit
 
Automating Front-End Workflow
Automating Front-End WorkflowAutomating Front-End Workflow
Automating Front-End Workflow
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php Presentation
 
Mastering Grails 3 Plugins - G3 Summit 2016
Mastering Grails 3 Plugins - G3 Summit 2016Mastering Grails 3 Plugins - G3 Summit 2016
Mastering Grails 3 Plugins - G3 Summit 2016
 
Django
DjangoDjango
Django
 

Kürzlich hochgeladen

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Kürzlich hochgeladen (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

Projeto-web-services-Spring-Boot-JPA.pdf

  • 1. Curso Java COMPLETO educandoweb.com Dr. Nelio Alves Projeto web services com Spring Boot e JPA / Hibernate Objetivos  Criar projeto Spring Boot Java  Implementar modelo de domínio  Estruturar camadas lógicas: resource, service, repository  Configurar banco de dados de teste (H2)  Povoar o banco de dados  CRUD - Create, Retrieve, Update, Delete  Tratamento de exceções Github: https://github.com/acenelio/workshop-springboot2-jpa
  • 5. Project created Checklist:  File -> New -> Spring Starter Project o Maven o Java 11 o Packing JAR o Dependencies: Spring Web Starter User entity and resource Basic entity checklist:  Basic attributes  Associations (instantiate collections)  Constructors  Getters & Setters (collections: only get)  hashCode & equals  Serializable H2 database, test profile, JPA Checklist:  JPA & H2 dependencies  application.properties  application-test.properties  Entity: JPA mapping Dependencies: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> application.properties: spring.profiles.active=test spring.jpa.open-in-view=true
  • 6. application-test.properties: spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.username=sa spring.datasource.password= spring.h2.console.enabled=true spring.h2.console.path=/h2-console spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true JPA repository, dependency injection, database seeding Checklist:  UserRepository extends JPARepository<User, Long>  Configuration class for "test" profile  @Autowired UserRepository  Instantiate objects in memory  Persist objects Objects: User u1 = new User(null, "Maria Brown", "maria@gmail.com", "988888888", "123456"); User u2 = new User(null, "Alex Green", "alex@gmail.com", "977777777", "123456"); Service layer, component registration Order, Instant, ISO 8601 Basic new entity checklist:  Entity o "To many" association, lazy loading, JsonIgnore  Repository  Seed  Service  Resource Objects: Order o1 = new Order(null, Instant.parse("2019-06-20T19:53:07Z"), u1); Order o2 = new Order(null, Instant.parse("2019-07-21T03:42:10Z"), u2); Order o3 = new Order(null, Instant.parse("2019-07-22T15:21:22Z"), u1);
  • 7. OrderStatus enum Category Objects: Category cat1 = new Category(null, "Electronics"); Category cat2 = new Category(null, "Books"); Category cat3 = new Category(null, "Computers"); Product Objects: Product p1 = new Product(null, "The Lord of the Rings", "Lorem ipsum dolor sit amet, consectetur.", 90.5, ""); Product p2 = new Product(null, "Smart TV", "Nulla eu imperdiet purus. Maecenas ante.", 2190.0, ""); Product p3 = new Product(null, "Macbook Pro", "Nam eleifend maximus tortor, at mollis.", 1250.0, ""); Product p4 = new Product(null, "PC Gamer", "Donec aliquet odio ac rhoncus cursus.", 1200.0, ""); Product p5 = new Product(null, "Rails for Dummies", "Cras fringilla convallis sem vel faucibus.", 100.99, ""); Many-to-many association with JoinTable OrderItem, many-to-many association with extra attributes Checklist:  OrderItemPK  OrderItem  Order one-to-many association  Seed Objects: OrderItem oi1 = new OrderItem(o1, p1, 2, p1.getPrice()); OrderItem oi2 = new OrderItem(o1, p3, 1, p3.getPrice()); OrderItem oi3 = new OrderItem(o2, p3, 2, p3.getPrice()); OrderItem oi4 = new OrderItem(o3, p5, 2, p5.getPrice()); Product-OrderItem one-to-many association Payment, one-to-one association Subtotal & Total methods
  • 8. User insert Checklist:  UserService  UserResource Test: { "name": "Bob Brown", "email": "bob@gmail.com", "phone": "977557755", "password": "123456" } User delete Checklist:  UserService  UserResource User update Checklist:  UserService  UserResource Test: { "name": "Bob Brown", "email": "bob@gmail.com", "phone": "977557755" } Exception handling - findById Checklist:  NEW CLASS: services.exceptions.ResourceNotFoundException  NEW CLASS: resources.exceptions.StandardError  NEW CLASS: resources.exceptions.ResourceExceptionHandler  UserService
  • 9. Exception handling - delete Checklist:  NEW CLASS: services.exceptions.DatabaseException  ResourceExceptionHandler  UserService o EmptyResultDataAccessException o DataIntegrityViolationException Exception handling - update Checklist:  UserService o EntityNotFoundException Create Heroku app & provision PostgreSQL Checklist:  Heroku Sign Up  Create app  Provision PostgreSQL o App dashboard -> Resources o Search "postgres" -> select "Heroku Postgres" Install local PostgreSQL Checklist:  Download and install: https://www.postgresql.org/download/ o Super user: postgres o Password: 1234567 o Port: 5432  Start/stop service: Task manager -> Services  Check instalation o Start pgAdmin o Databases -> Create -> Database  Encoding: UTF8
  • 10. Dev profile Checklist:  PgAdmin: create local database: create database springboot_course  Add PostgreSQL Maven dependency <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency>  Create file: application-dev.properties spring.datasource.url=jdbc:postgresql://localhost:5432/springboot_course spring.datasource.username=postgres spring.datasource.password=1234567 spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true jwt.secret=MYJWTSECRET jwt.expiration=3600000  Update application.properties: spring.profiles.active=dev  Run application Get SQL script from local PostgreSQL  PgAdmin: get SQL script: o Select database o Tools -> Backup  Format: Plain  Encoding: UTF8  Dump options:  Only schema: YES  Blobs: NO  Do not save: (ALL)  Verbose messages: NO  Delete instructions before CREATE statements
  • 11. Run SQL Script Checklist:  App dashboard -> Settings - > Config Vars EXAMPLE: postgres://wavglvupbdad:358f443aafe452eca4c58fbc15d02e50b08130c7aaea3aff6c4f59c 13f9abb@ec2-23-21-106-266.compute-1.amazonaws.com:5432/d7u9ub86cdsu user: wavglvupbdad password: 358f443aafe452eca4c58fbc15d02e50b08130c7aaea3aff6c4f59c13f9abb server: ec2-23-21-106-266.compute-1.amazonaws.com port: 5432 database: d7u9ub86cdsu  PgAdmin: Servers -> Create -> Server o Advanced -> DB rescriction: (database)  Database -> Query Tool o Load and run SQL Script Deploy app to Heroku  Heroku app dashboard -> Deploy heroku git:remote -a myapp git remote -v  Setup Heroku app Config Vars o DATABASE_URL o JWT_EXPIRATION o JWT_SECRET  Create: application-prod.properties spring.datasource.url=${DATABASE_URL} spring.jpa.hibernate.ddl-auto=none spring.jpa.show-sql=false spring.jpa.properties.hibernate.format_sql=false jwt.secret=${JWT_SECRET} jwt.expiration=${JWT_EXPIRATION}
  • 12.  Update application.properties: spring.profiles.active=prod  Create files: system.properties java.runtime.version=11  Send to Heroku: git add . git commit -m "Deploy app to Heroku" git push heroku master