SlideShare a Scribd company logo
© 2015 IBM Corporation
EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples [CON7535]
EJB 3.2/JPA 2.1 Best Practices with
Real-Life Examples
[CON7535]
Ahmad Gohar, Architect
IBM Experienced IT-Specialist
Client Innovation Center (CIC)
1
© 2015 IBM Corporation
Ahmad (Nabil) Gohar
Architect & Technical Team Lead (9Y.)
Client Innovation Center CIC | IBM Egypt
IBM Certified Experienced IT Specialist
M.Sc. in Information System, FCI, Egypt
MIBA in Global Management, ESLSCA, France
OCEJPA, OCPWCD,OCPJP, OCP PL/SQL, MCP(s)
JAVA Community Process (JCP) Member
Blogger Author and Academic Researcher2
© 2015 IBM Corporation
JavaOne 2015 Keynote
3
© 2015 IBM Corporation4
© 2015 IBM Corporation5
© 2015 IBM Corporation6
© 2015 IBM Corporation
ENCRYPT STRING DATA
Entity
7
© 2015 IBM Corporation
Data Model
Oracle HR Employees Table
8
© 2015 IBM Corporation
The EncryptorBean
The EncryptorBean handles encryption but does not
know what’s being encrypted.
9
© 2015 IBM Corporation
Encryption Main requirements
Provide a transparent encryption that does not
affect the application,
Develop application and security/encryption by two
different teams/persons.
10
© 2015 IBM Corporation
1- Encryption Using Facade
Facade
11
© 2015 IBM Corporation
1- Encryption Using Facade
Persistence manager quietly handles your
encryption
Architecture demands a tight and unnecessary
binding between your persistence and security
designs.
You can’t touch one without also touching the other.
12
© 2015 IBM Corporation
2- JPA EntityListeners
13
© 2015 IBM Corporation
2- JPA EntityListeners
 A solution is JPA EntityListeners
 These are Listener classes that can provide methods called before or after database object
creation, deletion or modification.
– @PrePersist
– @PreUpdate
– @PreRemove
– @PostLoad
– @PostUpdate
– @PostRemove
 To keep a clean separation between the persistence and security layers the listener does
nothing but call a service that handles the encryption.
14
© 2015 IBM Corporation
3- Converter (AttributeConverter) @JPA 2.1
Attribute Converter provide a nice and easy way to
define a custom mapping between your property on
the entity and the database column.
The only thing that is needed is a class that
–implements the AttributeConverter interface
–annotated with @Converter.
15
© 2015 IBM Corporation
Converter (AttributeConverter)
16
Converter Class
© 2015 IBM Corporation
Converter (AttributeConverter)
17
JPA
Facade
© 2015 IBM Corporation
Entity Listeners or Attribute Converter?
Entity Listener Adv.
The entity listener can use
multiple attributes of the
entity during encryption.
So we can join multiple
attributes, encrypt them
and store the encrypted
data in one database field.
Entity Listener Drawbacks
Its implementation is
specific for an entity
More complex than the
implementation of a
Attribute Converter.
If we need to encrypt an
additional attribute, you
need to change the
implementation.
18
© 2015 IBM Corporation
Entity Listeners or Attribute Converter?
The Converter Adv.
Can be used to encrypt
any String attribute of any
entity.
By using the XML based
configuration to register
the converter to the entity
attribute, it requires no
change in the source code
of the application.
The Converter Drawbacks
The encrypted entity
attribute cannot be marked
as transient.
This might result in
vulnerabilities if the entity
gets written to the disk.
19
© 2015 IBM Corporation
Entity Listeners or Attribute Converter?
Both approaches have their pros and cons.
You have to decide which advantages and
disadvantages are more important to you.
20
© 2015 IBM Corporation
ENCRYPT OBJECT DATA
Entity
21
© 2015 IBM Corporation
BigDecimal Converter
22
© 2015 IBM Corporation
BigDecimal Converter
23
Converter Class
© 2015 IBM Corporation
BigDecimal Converter
24
JPA
© 2015 IBM Corporation
JAVA 8 DATE TIME API
JSR 310
25
© 2015 IBM Corporation
Java 8 Date Time API
 A date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03.
 LocalDate is an immutable date-time object that represents a date.
 Other date fields, such as day-of-year, day-of-week and week-of-year, can also be
accessed.
 The ISO-8601 calendar system is the modern civil calendar system used today in most of
the world.
 However, any application that makes use of historical dates, and requires them to be
accurate will find the ISO-8601 approach unsuitable.
26
© 2015 IBM Corporation
Java 8 Date Time API
27
© 2015 IBM Corporation
Does JPA 2.1 support LocalDate and LocalDateTime?
The answer is simple,
JPA 2.1 was released before Java 8 and the Date and
Time API simply didn’t exist at that point in time.
Therefore the @Temporal annotation can only be applied
to attributes of type java.util.Date and java.util.Calendar.
28
Why JPA not support LocalDate and LocalDateTime?
NO
© 2015 IBM Corporation
HOW TO PERSIST
LOCALDATE AND
LOCALDATETIME WITH JPA
Entity
29
© 2015 IBM Corporation
How to persist LocalDate and LocalDateTime with JPA
30
Converter Class
© 2015 IBM Corporation
How to persist LocalDate and LocalDateTime with JPA
31
JPA
© 2015 IBM Corporation
Converting LocalDateTime
 The attribute converter for LocalDateTime is basically the same.
 You need to implement the AttributeConverter<LocalDateTime, Timestamp> interface and
the converter needs to be annotated with the @Converter annotation.
 Similar to the LocalDateConverter, the conversion between a LocalDateTime and an
java.sql.Timestamp is done with the conversion methods of Timestamp.
32
© 2015 IBM Corporation
LocalDate/LocalDateTime Conclusion
 JPA 2.1 was released before Java 8 and therefore doesn’t support the new Date and Time
API.
 If you want to use the new classes (in the right way), you need to define the conversion to
java.sql.Date and java.sql.Timestamp yourself.
 This can be easily done by implementing the AttributeConverter<EntityType, DatabaseType>
interface and annotating the class with @Converter(autoApply=true).
 By setting autoApply=true, the converter will be applied to all attributes of the EntityType and
no changes on the entity are required.
33
© 2015 IBM Corporation
DATA FETCHING STRATEGY
Entity
34
© 2015 IBM Corporation
Data fetching strategy
 EAGER – immediate
 LAZY – load only when needed
 Lazy is good for large objects with deep relationship hierarchies
35
© 2015 IBM Corporation
Lazy Loading Best Practices
 Lazy load fields and relationships that are not used frequently
 One-many/many-may relationships are lazy loaded by default
 Lazy load CLOB/BLOB if possible
 Accessing a LAZY relationship from a detached entity
– May get a null
– May get a previously cached value
– May get an exception
36
© 2015 IBM Corporation
WAYS TO INITIALIZE LAZY
RELATIONS
Entity | Data Fetching Strategy
37
© 2015 IBM Corporation
JPA
38
Example
© 2015 IBM Corporation
1. Call a method on the mapped relation
Facade
39
© 2015 IBM Corporation
2. Fetch Join in JPQL
Facade
40
JPA
© 2015 IBM Corporation
3. Fetch Join in Criteria API
Facade
41
© 2015 IBM Corporation
4. Named Entity Graph
JPA
Facade
42
© 2015 IBM Corporation
5. Dynamic Entity Graph
Facade
43
© 2015 IBM Corporation
5. Dynamic Entity Graph
Advantage
If we need lots of use case specific entity graphs, it might
be better to define the entity graph within the specific Java
code and to not add an additional annotation to the entity.
Avoids entities with dozens of annotations.
44
Disadvantage
The dynamic entity graph requires more code and an
additional method to be reusable.
© 2015 IBM Corporation
5 ways to initialize lazy relations and when to use them
 Initializing a lazy relation via calling a method on a mapped relation causes an additional
query. This should be avoided for performance reasons.
 Fetch joins in JPQL statements reduce the number of queries to one but we might need a lot
of different queries.
 The Criteria API also supports fetch joins and we need specific code for each combination of
relations that shall be initialized.
 Named entity graphs are a good solution, if we will reuse the defined graph in our code.
 Dynamic entity graphs can be the better solution, if we need to define a use case specific
graph.
45
© 2015 IBM Corporation
QUERIES
Schemas and Queries
46
© 2015 IBM Corporation
Query
JPQL
JPA Criteria
47
© 2015 IBM Corporation
Query
JPA Criteria with Metamodel
48
© 2015 IBM Corporation
DEFINE NAMED QUERIES AT
RUNTIME
Schemas and Queries
49
© 2015 IBM Corporation
3 steps to define a named query at runtime
1. Create a Query.
– This can be done as a JPQL, native or criteria query.
– You can also define additional hints and settings for the query.
1. Find a name for your query that is unique within your persistence unit.
– If there is already a named query defined for the name, the query will be updated.
1. Use the Query and name to call the addNamedQuery(String name, Query query) method
on the EntityManagerFactory.
50
© 2015 IBM Corporation
Named Query at Runtime
Define the Named Query
Call the Named Query
51
© 2015 IBM Corporation
JPQL ENHANCEMENTS
Schemas and Queries
52
© 2015 IBM Corporation
JPQL enhancements
We can now use the keyword ON to define
additional join parameters
call database functions by using FUNCTION
downcast entities with TREAT.
53
© 2015 IBM Corporation
JPQL enhancement (FUNC)
54
© 2015 IBM Corporation
BULK UPDATES
Schemas and Queries
55
© 2015 IBM Corporation
Bulk Updates
56
© 2015 IBM Corporation
Bulk Updates
57
© 2015 IBM Corporation
STORED PROCEDURES IN JPA
Schemas and Queries
58
© 2015 IBM Corporation
4 different modes of parameters
 IN:
– for input parameters,
 OUT:
– for output parameters,
 INOUT:
– for parameters which are used for input and output and
 REF_CURSOR:
– for cursors on a result set .
59
© 2015 IBM Corporation
Oracle Stored Procedure
60
© 2015 IBM Corporation
Named Stored Procedure
61
© 2015 IBM Corporation
Named Stored Procedure
62
© 2015 IBM Corporation
Stored Procedure Query
63
© 2015 IBM Corporation
GENERATING DB SCHEMA
Schemas and Queries
64
© 2015 IBM Corporation
Generating DB Schema
 javax.persistence.schema-generation.database.action
 javax.persistence.schema-generation.scripts.action
 javax.persistence.schema-generation.create-source
 javax.persistence.schema-generation.drop-source
 javax.persistence.schema-generation.create-database-schemas
 javax.persistence.schema-generation.scripts.create-target
 javax.persistence.schema-generation.scripts.drop-target
 javax.persistence.database-product-name
 javax.persistence.database-major-version
 javax.persistence.database-minor-version
 javax.persistence.schema-generation.create-script-source
 javax.persistence.schema-generation.drop-script-source
 javax.persistence.schema-generation.connection
 javax.persistence.sql-load-script-source
65
© 2015 IBM Corporation
EJB LITE
EJB
66
© 2015 IBM Corporation
More features in EJB.Lite
Asynchronous session bean
Non-persistent EJB Timer service
67
© 2015 IBM Corporation
STATEFUL SESSION BEAN
EJB
68
© 2015 IBM Corporation
Stateful Session Bean Life Cycle
69
© 2015 IBM Corporation
Opt-out of passivation for stateful session bean
70
© 2015 IBM Corporation
TIMERSERVICE
EJB
71
© 2015 IBM Corporation
TimerService
 TimerService.getAllTimers
– a newly added convenience API that returns all timers in the same bean.
– This is only for displaying the list of timers as the timer can only be cancelled by its
owner.
72
© 2015 IBM Corporation
Painless Persistence
Invest in some JPA skills
Design your persistent objects
Create a services layer (DAOs are not sufficient)
Avoid cool but expensive features (e.g. Cascade)
and always work with the DBAs
Don't blindly do anything – always think before you
code!
73
© 2015 IBM Corporation
Wrap up
74
© 2015 IBM Corporation
Wrap up
75
Encrypt String Data (AttributeConverter)
Encrypt Object Data (AttributeConverter)
Java 8 Date Time API (AttributeConverter)
Data fetching strategy
ways to initialize lazy relations(Named Entity Graph, Dynamic Entity
Graph)
Bulk Updates (Criteria Update)
stored procedures in JPA (Named Stored Procedure, Stored Procedure
Query)
define named queries at runtime
JPQL Enhancements
© 2015 IBM Corporation
Q. & A.
76
https://about.me/ansgohar
http://ansgohar.blogspot.co.uk
https://eg.linkedin.com/in/ansgohar
https://www.facebook.com/ansgohar
https://twitter.com/ansgohar
ansgoharansgohar
© 2015 IBM Corporation77
© 2015 IBM Corporation
78

More Related Content

What's hot

Migration tales from java ee 5 to 7
Migration tales from java ee 5 to 7Migration tales from java ee 5 to 7
Migration tales from java ee 5 to 7
Roberto Cortez
 
JavaOne 2015: 12 Factor App
JavaOne 2015: 12 Factor AppJavaOne 2015: 12 Factor App
JavaOne 2015: 12 Factor App
Joe Kutner
 
Microservices - java ee vs spring boot and spring cloud
Microservices - java ee vs spring boot and spring cloudMicroservices - java ee vs spring boot and spring cloud
Microservices - java ee vs spring boot and spring cloud
Ben Wilcock
 
Test Policy and Practices
Test Policy and PracticesTest Policy and Practices
Test Policy and Practices
Talentica Software
 
Workshop Framework(J2EE/OSGi/RCP)
Workshop Framework(J2EE/OSGi/RCP)Workshop Framework(J2EE/OSGi/RCP)
Workshop Framework(J2EE/OSGi/RCP)
Summer Lu
 
Java Concurrent
Java ConcurrentJava Concurrent
Java Concurrent
NexThoughts Technologies
 
Lessons Learned from Real-World Deployments of Java EE 7 at JavaOne 2014
Lessons Learned from Real-World Deployments of Java EE 7 at JavaOne 2014Lessons Learned from Real-World Deployments of Java EE 7 at JavaOne 2014
Lessons Learned from Real-World Deployments of Java EE 7 at JavaOne 2014
Arun Gupta
 
Java Application Servers Are Dead!
Java Application Servers Are Dead!Java Application Servers Are Dead!
Java Application Servers Are Dead!
Eberhard Wolff
 
Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design Patterns
Steven Smith
 
Maven - Taming the Beast
Maven - Taming the BeastMaven - Taming the Beast
Maven - Taming the Beast
Roberto Cortez
 
Take your CFML Legacy Apps to Modernization
Take your CFML Legacy Apps to ModernizationTake your CFML Legacy Apps to Modernization
Take your CFML Legacy Apps to Modernization
Ortus Solutions, Corp
 
FAST for SharePoint Deep Dive
FAST for SharePoint Deep DiveFAST for SharePoint Deep Dive
FAST for SharePoint Deep Dive
neil_richards
 
ColdBox Hierarchical MVC - Transform Your Monolith
ColdBox Hierarchical MVC - Transform Your MonolithColdBox Hierarchical MVC - Transform Your Monolith
ColdBox Hierarchical MVC - Transform Your Monolith
Ortus Solutions, Corp
 
Cakephp vs. laravel
Cakephp vs. laravelCakephp vs. laravel
Cakephp vs. laravel
GirnarSoft
 
12 Factor Scala
12 Factor Scala12 Factor Scala
12 Factor Scala
Joe Kutner
 
Ruby Under The Hood
Ruby Under The HoodRuby Under The Hood
Ruby Under The Hood
craig lehmann
 
Digpen 7: Why choose Laravel?
Digpen 7: Why choose Laravel?Digpen 7: Why choose Laravel?
Digpen 7: Why choose Laravel?
John Blackmore
 
SynapseIndia drupal presentation on drupal info
SynapseIndia drupal  presentation on drupal infoSynapseIndia drupal  presentation on drupal info
SynapseIndia drupal presentation on drupal info
Synapseindiappsdevelopment
 
Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design of Existing Software
Steven Smith
 
Saving Time By Testing With Jest
Saving Time By Testing With JestSaving Time By Testing With Jest
Saving Time By Testing With Jest
Ben McCormick
 

What's hot (20)

Migration tales from java ee 5 to 7
Migration tales from java ee 5 to 7Migration tales from java ee 5 to 7
Migration tales from java ee 5 to 7
 
JavaOne 2015: 12 Factor App
JavaOne 2015: 12 Factor AppJavaOne 2015: 12 Factor App
JavaOne 2015: 12 Factor App
 
Microservices - java ee vs spring boot and spring cloud
Microservices - java ee vs spring boot and spring cloudMicroservices - java ee vs spring boot and spring cloud
Microservices - java ee vs spring boot and spring cloud
 
Test Policy and Practices
Test Policy and PracticesTest Policy and Practices
Test Policy and Practices
 
Workshop Framework(J2EE/OSGi/RCP)
Workshop Framework(J2EE/OSGi/RCP)Workshop Framework(J2EE/OSGi/RCP)
Workshop Framework(J2EE/OSGi/RCP)
 
Java Concurrent
Java ConcurrentJava Concurrent
Java Concurrent
 
Lessons Learned from Real-World Deployments of Java EE 7 at JavaOne 2014
Lessons Learned from Real-World Deployments of Java EE 7 at JavaOne 2014Lessons Learned from Real-World Deployments of Java EE 7 at JavaOne 2014
Lessons Learned from Real-World Deployments of Java EE 7 at JavaOne 2014
 
Java Application Servers Are Dead!
Java Application Servers Are Dead!Java Application Servers Are Dead!
Java Application Servers Are Dead!
 
Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design Patterns
 
Maven - Taming the Beast
Maven - Taming the BeastMaven - Taming the Beast
Maven - Taming the Beast
 
Take your CFML Legacy Apps to Modernization
Take your CFML Legacy Apps to ModernizationTake your CFML Legacy Apps to Modernization
Take your CFML Legacy Apps to Modernization
 
FAST for SharePoint Deep Dive
FAST for SharePoint Deep DiveFAST for SharePoint Deep Dive
FAST for SharePoint Deep Dive
 
ColdBox Hierarchical MVC - Transform Your Monolith
ColdBox Hierarchical MVC - Transform Your MonolithColdBox Hierarchical MVC - Transform Your Monolith
ColdBox Hierarchical MVC - Transform Your Monolith
 
Cakephp vs. laravel
Cakephp vs. laravelCakephp vs. laravel
Cakephp vs. laravel
 
12 Factor Scala
12 Factor Scala12 Factor Scala
12 Factor Scala
 
Ruby Under The Hood
Ruby Under The HoodRuby Under The Hood
Ruby Under The Hood
 
Digpen 7: Why choose Laravel?
Digpen 7: Why choose Laravel?Digpen 7: Why choose Laravel?
Digpen 7: Why choose Laravel?
 
SynapseIndia drupal presentation on drupal info
SynapseIndia drupal  presentation on drupal infoSynapseIndia drupal  presentation on drupal info
SynapseIndia drupal presentation on drupal info
 
Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design of Existing Software
 
Saving Time By Testing With Jest
Saving Time By Testing With JestSaving Time By Testing With Jest
Saving Time By Testing With Jest
 

Viewers also liked

Hibernate ve jpa
Hibernate ve jpaHibernate ve jpa
Hibernate ve jpa
Orçun Çolak
 
ICT and travel avoidance
ICT and travel avoidanceICT and travel avoidance
ICT and travel avoidance
Smartgo Leicester
 
Hibernate ve jpa
Hibernate ve jpaHibernate ve jpa
Hibernate ve jpa
Orçun Çolak
 
Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"
Anna Shymchenko
 
JPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsJPA 2.1 performance tuning tips
JPA 2.1 performance tuning tips
osa_ora
 
JPA - Java Persistence API
JPA - Java Persistence APIJPA - Java Persistence API
JPA - Java Persistence API
Thomas Wöhlke
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
elliando dias
 
JPA Best Practices
JPA Best PracticesJPA Best Practices
JPA Best Practices
Carol McDonald
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
Guo Albert
 

Viewers also liked (9)

Hibernate ve jpa
Hibernate ve jpaHibernate ve jpa
Hibernate ve jpa
 
ICT and travel avoidance
ICT and travel avoidanceICT and travel avoidance
ICT and travel avoidance
 
Hibernate ve jpa
Hibernate ve jpaHibernate ve jpa
Hibernate ve jpa
 
Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"
 
JPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsJPA 2.1 performance tuning tips
JPA 2.1 performance tuning tips
 
JPA - Java Persistence API
JPA - Java Persistence APIJPA - Java Persistence API
JPA - Java Persistence API
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
JPA Best Practices
JPA Best PracticesJPA Best Practices
JPA Best Practices
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 

Similar to EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples - CON7535

Pivotal microservices spring_pcf_skillsmatter.pptx
Pivotal microservices spring_pcf_skillsmatter.pptxPivotal microservices spring_pcf_skillsmatter.pptx
Pivotal microservices spring_pcf_skillsmatter.pptx
Sufyaan Kazi
 
JavaMicroBenchmarkpptm
JavaMicroBenchmarkpptmJavaMicroBenchmarkpptm
JavaMicroBenchmarkpptm
Srinivasan Raghavan
 
Vision2015-CBS-1148-Final
Vision2015-CBS-1148-FinalVision2015-CBS-1148-Final
Vision2015-CBS-1148-Final
Patrick Spedding
 
j2ee Building components
j2ee Building components j2ee Building components
j2ee Building components
adeppathondur
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
apidays LIVE Helsinki & North - Ideas around automating API Management by Mat...
apidays LIVE Helsinki & North - Ideas around automating API Management by Mat...apidays LIVE Helsinki & North - Ideas around automating API Management by Mat...
apidays LIVE Helsinki & North - Ideas around automating API Management by Mat...
apidays
 
TenYearsCPOptimizer
TenYearsCPOptimizerTenYearsCPOptimizer
TenYearsCPOptimizer
PaulShawIBM
 
RDz for DevOps Webcast Series: Implementing Continuous Integration with RDz
RDz for DevOps Webcast Series: Implementing Continuous Integration with RDzRDz for DevOps Webcast Series: Implementing Continuous Integration with RDz
RDz for DevOps Webcast Series: Implementing Continuous Integration with RDz
Susan Yoskin
 
MuleSoft Manchester Meetup #3 slides 31st March 2020
MuleSoft Manchester Meetup #3 slides 31st March 2020MuleSoft Manchester Meetup #3 slides 31st March 2020
MuleSoft Manchester Meetup #3 slides 31st March 2020
Ieva Navickaite
 
Grokking Techtalk #40: AWS’s philosophy on designing MLOps platform
Grokking Techtalk #40: AWS’s philosophy on designing MLOps platformGrokking Techtalk #40: AWS’s philosophy on designing MLOps platform
Grokking Techtalk #40: AWS’s philosophy on designing MLOps platform
Grokking VN
 
Making the Dinosaur Dance - RDz, RTC and UrbanCode Lunch and Learn slides
Making the Dinosaur Dance - RDz, RTC and UrbanCode Lunch and Learn slidesMaking the Dinosaur Dance - RDz, RTC and UrbanCode Lunch and Learn slides
Making the Dinosaur Dance - RDz, RTC and UrbanCode Lunch and Learn slides
Susan Yoskin
 
NTTs Journey with Openstack-final
NTTs Journey with Openstack-finalNTTs Journey with Openstack-final
NTTs Journey with Openstack-final
shintaro mizuno
 
Request Cloud.pptx
Request Cloud.pptxRequest Cloud.pptx
Request Cloud.pptx
FacultyofIT2
 
Amazon CI/CD Practices for Software Development Teams - SRV320 - Anaheim AWS ...
Amazon CI/CD Practices for Software Development Teams - SRV320 - Anaheim AWS ...Amazon CI/CD Practices for Software Development Teams - SRV320 - Anaheim AWS ...
Amazon CI/CD Practices for Software Development Teams - SRV320 - Anaheim AWS ...
Amazon Web Services
 
Amazon CI/CD Practices for Software Development Teams - SRV320 - Atlanta AWS ...
Amazon CI/CD Practices for Software Development Teams - SRV320 - Atlanta AWS ...Amazon CI/CD Practices for Software Development Teams - SRV320 - Atlanta AWS ...
Amazon CI/CD Practices for Software Development Teams - SRV320 - Atlanta AWS ...
Amazon Web Services
 
Removing Crucial Dependencies to Enable KPN as a Virtual Telecom Provider
Removing Crucial Dependencies to Enable KPN as a Virtual Telecom ProviderRemoving Crucial Dependencies to Enable KPN as a Virtual Telecom Provider
Removing Crucial Dependencies to Enable KPN as a Virtual Telecom Provider
CA Technologies
 
S109 cics-java
S109 cics-javaS109 cics-java
S109 cics-java
nick_garrod
 
JDK versions and OpenJDK
JDK versions and OpenJDKJDK versions and OpenJDK
JDK versions and OpenJDK
Wolfgang Weigend
 
How NBCUniversal Adopted DevOps
How NBCUniversal Adopted DevOpsHow NBCUniversal Adopted DevOps
How NBCUniversal Adopted DevOps
Sanjeev Sharma
 
Skytap parasoft webinar new years resolution- accelerate sdlc
Skytap parasoft webinar new years resolution- accelerate sdlcSkytap parasoft webinar new years resolution- accelerate sdlc
Skytap parasoft webinar new years resolution- accelerate sdlc
Skytap Cloud
 

Similar to EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples - CON7535 (20)

Pivotal microservices spring_pcf_skillsmatter.pptx
Pivotal microservices spring_pcf_skillsmatter.pptxPivotal microservices spring_pcf_skillsmatter.pptx
Pivotal microservices spring_pcf_skillsmatter.pptx
 
JavaMicroBenchmarkpptm
JavaMicroBenchmarkpptmJavaMicroBenchmarkpptm
JavaMicroBenchmarkpptm
 
Vision2015-CBS-1148-Final
Vision2015-CBS-1148-FinalVision2015-CBS-1148-Final
Vision2015-CBS-1148-Final
 
j2ee Building components
j2ee Building components j2ee Building components
j2ee Building components
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
apidays LIVE Helsinki & North - Ideas around automating API Management by Mat...
apidays LIVE Helsinki & North - Ideas around automating API Management by Mat...apidays LIVE Helsinki & North - Ideas around automating API Management by Mat...
apidays LIVE Helsinki & North - Ideas around automating API Management by Mat...
 
TenYearsCPOptimizer
TenYearsCPOptimizerTenYearsCPOptimizer
TenYearsCPOptimizer
 
RDz for DevOps Webcast Series: Implementing Continuous Integration with RDz
RDz for DevOps Webcast Series: Implementing Continuous Integration with RDzRDz for DevOps Webcast Series: Implementing Continuous Integration with RDz
RDz for DevOps Webcast Series: Implementing Continuous Integration with RDz
 
MuleSoft Manchester Meetup #3 slides 31st March 2020
MuleSoft Manchester Meetup #3 slides 31st March 2020MuleSoft Manchester Meetup #3 slides 31st March 2020
MuleSoft Manchester Meetup #3 slides 31st March 2020
 
Grokking Techtalk #40: AWS’s philosophy on designing MLOps platform
Grokking Techtalk #40: AWS’s philosophy on designing MLOps platformGrokking Techtalk #40: AWS’s philosophy on designing MLOps platform
Grokking Techtalk #40: AWS’s philosophy on designing MLOps platform
 
Making the Dinosaur Dance - RDz, RTC and UrbanCode Lunch and Learn slides
Making the Dinosaur Dance - RDz, RTC and UrbanCode Lunch and Learn slidesMaking the Dinosaur Dance - RDz, RTC and UrbanCode Lunch and Learn slides
Making the Dinosaur Dance - RDz, RTC and UrbanCode Lunch and Learn slides
 
NTTs Journey with Openstack-final
NTTs Journey with Openstack-finalNTTs Journey with Openstack-final
NTTs Journey with Openstack-final
 
Request Cloud.pptx
Request Cloud.pptxRequest Cloud.pptx
Request Cloud.pptx
 
Amazon CI/CD Practices for Software Development Teams - SRV320 - Anaheim AWS ...
Amazon CI/CD Practices for Software Development Teams - SRV320 - Anaheim AWS ...Amazon CI/CD Practices for Software Development Teams - SRV320 - Anaheim AWS ...
Amazon CI/CD Practices for Software Development Teams - SRV320 - Anaheim AWS ...
 
Amazon CI/CD Practices for Software Development Teams - SRV320 - Atlanta AWS ...
Amazon CI/CD Practices for Software Development Teams - SRV320 - Atlanta AWS ...Amazon CI/CD Practices for Software Development Teams - SRV320 - Atlanta AWS ...
Amazon CI/CD Practices for Software Development Teams - SRV320 - Atlanta AWS ...
 
Removing Crucial Dependencies to Enable KPN as a Virtual Telecom Provider
Removing Crucial Dependencies to Enable KPN as a Virtual Telecom ProviderRemoving Crucial Dependencies to Enable KPN as a Virtual Telecom Provider
Removing Crucial Dependencies to Enable KPN as a Virtual Telecom Provider
 
S109 cics-java
S109 cics-javaS109 cics-java
S109 cics-java
 
JDK versions and OpenJDK
JDK versions and OpenJDKJDK versions and OpenJDK
JDK versions and OpenJDK
 
How NBCUniversal Adopted DevOps
How NBCUniversal Adopted DevOpsHow NBCUniversal Adopted DevOps
How NBCUniversal Adopted DevOps
 
Skytap parasoft webinar new years resolution- accelerate sdlc
Skytap parasoft webinar new years resolution- accelerate sdlcSkytap parasoft webinar new years resolution- accelerate sdlc
Skytap parasoft webinar new years resolution- accelerate sdlc
 

Recently uploaded

AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
kalichargn70th171
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
pavan998932
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
Gerardo Pardo-Castellote
 

Recently uploaded (20)

AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
 

EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples - CON7535

  • 1. © 2015 IBM Corporation EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples [CON7535] EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples [CON7535] Ahmad Gohar, Architect IBM Experienced IT-Specialist Client Innovation Center (CIC) 1
  • 2. © 2015 IBM Corporation Ahmad (Nabil) Gohar Architect & Technical Team Lead (9Y.) Client Innovation Center CIC | IBM Egypt IBM Certified Experienced IT Specialist M.Sc. in Information System, FCI, Egypt MIBA in Global Management, ESLSCA, France OCEJPA, OCPWCD,OCPJP, OCP PL/SQL, MCP(s) JAVA Community Process (JCP) Member Blogger Author and Academic Researcher2
  • 3. © 2015 IBM Corporation JavaOne 2015 Keynote 3
  • 4. © 2015 IBM Corporation4
  • 5. © 2015 IBM Corporation5
  • 6. © 2015 IBM Corporation6
  • 7. © 2015 IBM Corporation ENCRYPT STRING DATA Entity 7
  • 8. © 2015 IBM Corporation Data Model Oracle HR Employees Table 8
  • 9. © 2015 IBM Corporation The EncryptorBean The EncryptorBean handles encryption but does not know what’s being encrypted. 9
  • 10. © 2015 IBM Corporation Encryption Main requirements Provide a transparent encryption that does not affect the application, Develop application and security/encryption by two different teams/persons. 10
  • 11. © 2015 IBM Corporation 1- Encryption Using Facade Facade 11
  • 12. © 2015 IBM Corporation 1- Encryption Using Facade Persistence manager quietly handles your encryption Architecture demands a tight and unnecessary binding between your persistence and security designs. You can’t touch one without also touching the other. 12
  • 13. © 2015 IBM Corporation 2- JPA EntityListeners 13
  • 14. © 2015 IBM Corporation 2- JPA EntityListeners  A solution is JPA EntityListeners  These are Listener classes that can provide methods called before or after database object creation, deletion or modification. – @PrePersist – @PreUpdate – @PreRemove – @PostLoad – @PostUpdate – @PostRemove  To keep a clean separation between the persistence and security layers the listener does nothing but call a service that handles the encryption. 14
  • 15. © 2015 IBM Corporation 3- Converter (AttributeConverter) @JPA 2.1 Attribute Converter provide a nice and easy way to define a custom mapping between your property on the entity and the database column. The only thing that is needed is a class that –implements the AttributeConverter interface –annotated with @Converter. 15
  • 16. © 2015 IBM Corporation Converter (AttributeConverter) 16 Converter Class
  • 17. © 2015 IBM Corporation Converter (AttributeConverter) 17 JPA Facade
  • 18. © 2015 IBM Corporation Entity Listeners or Attribute Converter? Entity Listener Adv. The entity listener can use multiple attributes of the entity during encryption. So we can join multiple attributes, encrypt them and store the encrypted data in one database field. Entity Listener Drawbacks Its implementation is specific for an entity More complex than the implementation of a Attribute Converter. If we need to encrypt an additional attribute, you need to change the implementation. 18
  • 19. © 2015 IBM Corporation Entity Listeners or Attribute Converter? The Converter Adv. Can be used to encrypt any String attribute of any entity. By using the XML based configuration to register the converter to the entity attribute, it requires no change in the source code of the application. The Converter Drawbacks The encrypted entity attribute cannot be marked as transient. This might result in vulnerabilities if the entity gets written to the disk. 19
  • 20. © 2015 IBM Corporation Entity Listeners or Attribute Converter? Both approaches have their pros and cons. You have to decide which advantages and disadvantages are more important to you. 20
  • 21. © 2015 IBM Corporation ENCRYPT OBJECT DATA Entity 21
  • 22. © 2015 IBM Corporation BigDecimal Converter 22
  • 23. © 2015 IBM Corporation BigDecimal Converter 23 Converter Class
  • 24. © 2015 IBM Corporation BigDecimal Converter 24 JPA
  • 25. © 2015 IBM Corporation JAVA 8 DATE TIME API JSR 310 25
  • 26. © 2015 IBM Corporation Java 8 Date Time API  A date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03.  LocalDate is an immutable date-time object that represents a date.  Other date fields, such as day-of-year, day-of-week and week-of-year, can also be accessed.  The ISO-8601 calendar system is the modern civil calendar system used today in most of the world.  However, any application that makes use of historical dates, and requires them to be accurate will find the ISO-8601 approach unsuitable. 26
  • 27. © 2015 IBM Corporation Java 8 Date Time API 27
  • 28. © 2015 IBM Corporation Does JPA 2.1 support LocalDate and LocalDateTime? The answer is simple, JPA 2.1 was released before Java 8 and the Date and Time API simply didn’t exist at that point in time. Therefore the @Temporal annotation can only be applied to attributes of type java.util.Date and java.util.Calendar. 28 Why JPA not support LocalDate and LocalDateTime? NO
  • 29. © 2015 IBM Corporation HOW TO PERSIST LOCALDATE AND LOCALDATETIME WITH JPA Entity 29
  • 30. © 2015 IBM Corporation How to persist LocalDate and LocalDateTime with JPA 30 Converter Class
  • 31. © 2015 IBM Corporation How to persist LocalDate and LocalDateTime with JPA 31 JPA
  • 32. © 2015 IBM Corporation Converting LocalDateTime  The attribute converter for LocalDateTime is basically the same.  You need to implement the AttributeConverter<LocalDateTime, Timestamp> interface and the converter needs to be annotated with the @Converter annotation.  Similar to the LocalDateConverter, the conversion between a LocalDateTime and an java.sql.Timestamp is done with the conversion methods of Timestamp. 32
  • 33. © 2015 IBM Corporation LocalDate/LocalDateTime Conclusion  JPA 2.1 was released before Java 8 and therefore doesn’t support the new Date and Time API.  If you want to use the new classes (in the right way), you need to define the conversion to java.sql.Date and java.sql.Timestamp yourself.  This can be easily done by implementing the AttributeConverter<EntityType, DatabaseType> interface and annotating the class with @Converter(autoApply=true).  By setting autoApply=true, the converter will be applied to all attributes of the EntityType and no changes on the entity are required. 33
  • 34. © 2015 IBM Corporation DATA FETCHING STRATEGY Entity 34
  • 35. © 2015 IBM Corporation Data fetching strategy  EAGER – immediate  LAZY – load only when needed  Lazy is good for large objects with deep relationship hierarchies 35
  • 36. © 2015 IBM Corporation Lazy Loading Best Practices  Lazy load fields and relationships that are not used frequently  One-many/many-may relationships are lazy loaded by default  Lazy load CLOB/BLOB if possible  Accessing a LAZY relationship from a detached entity – May get a null – May get a previously cached value – May get an exception 36
  • 37. © 2015 IBM Corporation WAYS TO INITIALIZE LAZY RELATIONS Entity | Data Fetching Strategy 37
  • 38. © 2015 IBM Corporation JPA 38 Example
  • 39. © 2015 IBM Corporation 1. Call a method on the mapped relation Facade 39
  • 40. © 2015 IBM Corporation 2. Fetch Join in JPQL Facade 40 JPA
  • 41. © 2015 IBM Corporation 3. Fetch Join in Criteria API Facade 41
  • 42. © 2015 IBM Corporation 4. Named Entity Graph JPA Facade 42
  • 43. © 2015 IBM Corporation 5. Dynamic Entity Graph Facade 43
  • 44. © 2015 IBM Corporation 5. Dynamic Entity Graph Advantage If we need lots of use case specific entity graphs, it might be better to define the entity graph within the specific Java code and to not add an additional annotation to the entity. Avoids entities with dozens of annotations. 44 Disadvantage The dynamic entity graph requires more code and an additional method to be reusable.
  • 45. © 2015 IBM Corporation 5 ways to initialize lazy relations and when to use them  Initializing a lazy relation via calling a method on a mapped relation causes an additional query. This should be avoided for performance reasons.  Fetch joins in JPQL statements reduce the number of queries to one but we might need a lot of different queries.  The Criteria API also supports fetch joins and we need specific code for each combination of relations that shall be initialized.  Named entity graphs are a good solution, if we will reuse the defined graph in our code.  Dynamic entity graphs can be the better solution, if we need to define a use case specific graph. 45
  • 46. © 2015 IBM Corporation QUERIES Schemas and Queries 46
  • 47. © 2015 IBM Corporation Query JPQL JPA Criteria 47
  • 48. © 2015 IBM Corporation Query JPA Criteria with Metamodel 48
  • 49. © 2015 IBM Corporation DEFINE NAMED QUERIES AT RUNTIME Schemas and Queries 49
  • 50. © 2015 IBM Corporation 3 steps to define a named query at runtime 1. Create a Query. – This can be done as a JPQL, native or criteria query. – You can also define additional hints and settings for the query. 1. Find a name for your query that is unique within your persistence unit. – If there is already a named query defined for the name, the query will be updated. 1. Use the Query and name to call the addNamedQuery(String name, Query query) method on the EntityManagerFactory. 50
  • 51. © 2015 IBM Corporation Named Query at Runtime Define the Named Query Call the Named Query 51
  • 52. © 2015 IBM Corporation JPQL ENHANCEMENTS Schemas and Queries 52
  • 53. © 2015 IBM Corporation JPQL enhancements We can now use the keyword ON to define additional join parameters call database functions by using FUNCTION downcast entities with TREAT. 53
  • 54. © 2015 IBM Corporation JPQL enhancement (FUNC) 54
  • 55. © 2015 IBM Corporation BULK UPDATES Schemas and Queries 55
  • 56. © 2015 IBM Corporation Bulk Updates 56
  • 57. © 2015 IBM Corporation Bulk Updates 57
  • 58. © 2015 IBM Corporation STORED PROCEDURES IN JPA Schemas and Queries 58
  • 59. © 2015 IBM Corporation 4 different modes of parameters  IN: – for input parameters,  OUT: – for output parameters,  INOUT: – for parameters which are used for input and output and  REF_CURSOR: – for cursors on a result set . 59
  • 60. © 2015 IBM Corporation Oracle Stored Procedure 60
  • 61. © 2015 IBM Corporation Named Stored Procedure 61
  • 62. © 2015 IBM Corporation Named Stored Procedure 62
  • 63. © 2015 IBM Corporation Stored Procedure Query 63
  • 64. © 2015 IBM Corporation GENERATING DB SCHEMA Schemas and Queries 64
  • 65. © 2015 IBM Corporation Generating DB Schema  javax.persistence.schema-generation.database.action  javax.persistence.schema-generation.scripts.action  javax.persistence.schema-generation.create-source  javax.persistence.schema-generation.drop-source  javax.persistence.schema-generation.create-database-schemas  javax.persistence.schema-generation.scripts.create-target  javax.persistence.schema-generation.scripts.drop-target  javax.persistence.database-product-name  javax.persistence.database-major-version  javax.persistence.database-minor-version  javax.persistence.schema-generation.create-script-source  javax.persistence.schema-generation.drop-script-source  javax.persistence.schema-generation.connection  javax.persistence.sql-load-script-source 65
  • 66. © 2015 IBM Corporation EJB LITE EJB 66
  • 67. © 2015 IBM Corporation More features in EJB.Lite Asynchronous session bean Non-persistent EJB Timer service 67
  • 68. © 2015 IBM Corporation STATEFUL SESSION BEAN EJB 68
  • 69. © 2015 IBM Corporation Stateful Session Bean Life Cycle 69
  • 70. © 2015 IBM Corporation Opt-out of passivation for stateful session bean 70
  • 71. © 2015 IBM Corporation TIMERSERVICE EJB 71
  • 72. © 2015 IBM Corporation TimerService  TimerService.getAllTimers – a newly added convenience API that returns all timers in the same bean. – This is only for displaying the list of timers as the timer can only be cancelled by its owner. 72
  • 73. © 2015 IBM Corporation Painless Persistence Invest in some JPA skills Design your persistent objects Create a services layer (DAOs are not sufficient) Avoid cool but expensive features (e.g. Cascade) and always work with the DBAs Don't blindly do anything – always think before you code! 73
  • 74. © 2015 IBM Corporation Wrap up 74
  • 75. © 2015 IBM Corporation Wrap up 75 Encrypt String Data (AttributeConverter) Encrypt Object Data (AttributeConverter) Java 8 Date Time API (AttributeConverter) Data fetching strategy ways to initialize lazy relations(Named Entity Graph, Dynamic Entity Graph) Bulk Updates (Criteria Update) stored procedures in JPA (Named Stored Procedure, Stored Procedure Query) define named queries at runtime JPQL Enhancements
  • 76. © 2015 IBM Corporation Q. & A. 76 https://about.me/ansgohar http://ansgohar.blogspot.co.uk https://eg.linkedin.com/in/ansgohar https://www.facebook.com/ansgohar https://twitter.com/ansgohar ansgoharansgohar
  • 77. © 2015 IBM Corporation77
  • 78. © 2015 IBM Corporation 78

Editor's Notes

  1. Did you attain the Keynote I will use two of the new features introduced there, One I love and other I may hate
  2. How many of you have hands on experiences on JPA 2SpeciallyJPA 2.1 EJB 3SpeciallyEJB 3.2
  3. May I have you attention please. Lets agree on that I will not share my experience with you OLNY RATHER you all will share yours with US ALSO Let us Make it interactive
  4. I Started with my Bio, So please replay with your expectations
  5. We only change the HR Emplyee table to increase the FIRST_NAME column size to accept the encoded characters
  6. From Architectural prespective
  7. You need to implement the AttributeConverter&amp;lt;String, String&amp;gt; interface with its two methods convertToDatabaseColumn and convertToEntityAttribute. As you can see on the method names, one of them defines the conversion from the type of the entity attribute (String) to the database column type (VARCHAR2) and the other one the inverse conversion.
  8. The answer for this question is not as easy as it seems. Both solutions have their advantages and disadvantages.
  9. JAVA------------Encryption-------- DB String------------Decryption-------- VARCHAR2 NOT What about other Object types like BigDecimal
  10. New Column added to the Employees table to store the encrypted value of the NET_SALARY
  11. JAVA------------------- BigDecimal DB------------------ VARCHAR2
  12. As we pointed out in the beginning, the encryption should work in a transparent way. That means, that the application is not affected by the encryption and that it can be added without any changes to the existing code base. For me, this also includes the data model in the database because it is often created by some application specific scripts which shall not be changed. So we need a Attribute Converter that does not change the data type while encrypting and decrypting the information.
  13. JRS 310 Wellcome to JDK 8
  14. Java 8 brought lots of great features and one of the most important and most anticipated ones was the new Date and Time API. There were lots of issues with the old API and I won’t get into any details on why we needed a new one. I’m sure you had to struggle often enough with it yourself. All these issues are gone with Java 8.
  15. The new Date and Time API is well designed, easy to use and (finally) immutable. The only issue that remains is, that you cannot use it with JPA. Well, that’s not completely correct. You can use it, but JPA will map it to a BLOB instead of a DATE or TIMESTAMP. That means the database is not aware of the date object and cannot apply any optimization for it.
  16. If you want to store a LocalDate attribute in a DATE column or a LocalDateTime in a TIMESTAMP column, you need to define the mapping to java.sql.Date or java.sql.Timestamp yourself. Thanks to the attribute converter
  17. Additionally the attribute converter needs to be annotated with the @Converter annotation. Due to the optional autoApply=true property, the converter will be applied to all attributes of type LocalDate. Have a look here, if you want to define the usage of the converter for each attribute individually.
  18. Additionally the attribute converter needs to be annotated with the @Converter annotation. Due to the optional autoApply=true property, the converter will be applied to all attributes of type LocalDate. NO NEED to @converter(converter=ClassName.class)
  19. As far as I know, the next JPA release will support the Date and Time API and the different implementations will probably support it even earlier.
  20. Deafult for most providers Lazy for 1 many and many  many Eager for 1One and many  one Eager VS Lazy Loading each one has its Proc and Cons
  21. Take care form the last point
  22. Lets assume this situation We have one  many relation in the JPA We need the same JPA Entity to retrive the many side in some situation and its big collection So in the cases of not needed we will not need to retrive it What can we DO? Suggestions PLZ
  23. Access any method in the collection Take care not access Clean method ha ha ha
  24. Access any method in the collection Take care not access Clean method ha ha ha
  25. Façade remain as it is And we generate two different Queries
  26. @JPA 2.1 It can be used to define a graph of entities that shall be queried from the database. The definition of an entity graph is done via annotations and is independent of the query.
  27. So I recommend to use dynamic entity graphs, if we need to define a use case specific graph, that will not be reused. If we want to reuse the entity graph, it is easier to annotate a named entity graph.
  28. So I recommend to use dynamic entity graphs, if we need to define a use case specific graph, that will not be reused. If we want to reuse the entity graph, it is easier to annotate a named entity graph.
  29. “Salary”
  30. “MetaModel data” it may be little change but it minimize the error of String manibulatiuons • Dynamically creates query without out string manipulation • Strongly type, compiler validation during development • Optionally can generate metamodel over entities
  31. Take care while using the Function Really I don’t prefer to use this JPQL functions as it makes the code database dependent and hide the portability of the JPQL code AS the Function is DB specific
  32. Let see an example of the Function usage
  33. There is also CriteriaDelete for Bulk delete
  34. JPA 2.1 introduced @NamedStoredProcedureQuery which can be used to declaratively define the stored procedure call. The stored procedure can use parameters of 4 different modes. IN, OUTand INOUT can be used to define simple input and output parameters. The REF_CURSOR type can be used to return the result of a query. After we have defined the @NamedStoredProcedureQuery, we can use the createNamedStoredProcedureQuery(String name) method of the EntityManager to create aStoredProcedureQuery object. This provides the required methods to set the input parameter, call the stored procedure and get the result.
  35. The programmatic creation of a StoredProcedureQuery is one of two options to define a stored procedure call in JPA. Therefore you have to call one of the createStoredProcedureQuerymethods on the entity manager and then you have to define the input and output parameters of the procedure. If your stored procedure returns a REF_CURSOR, you have to also provide some mapping information when creating the query. This can be done by naming entities for which the EntityManager can determine the mapping automatically or by using a result set mapping.
  36. Lets Start some HIT AND RUN Short Topics as we are run out of time
  37. Up to JPA 2.1 you needed to use vendor specific configuration parameter to define the database setup in the persistence.xml file. Starting from version 2.1 there is also a standard way to do this
  38. This also means these features can be used in embeddable EJB container and there by improving testability of your application.
  39. - If your stateful session bean needs to stick around or it has non-serializable field then the bean can be opt-out of passivation as shown.
  40. Some guidelines for creating persistent Java applications that work
  41. The presentation Code