SlideShare a Scribd company logo
1 of 78
© 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 7Roberto Cortez
 
JavaOne 2015: 12 Factor App
JavaOne 2015: 12 Factor AppJavaOne 2015: 12 Factor App
JavaOne 2015: 12 Factor AppJoe 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 cloudBen Wilcock
 
Workshop Framework(J2EE/OSGi/RCP)
Workshop Framework(J2EE/OSGi/RCP)Workshop Framework(J2EE/OSGi/RCP)
Workshop Framework(J2EE/OSGi/RCP)Summer Lu
 
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 2014Arun 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 PatternsSteven Smith
 
Maven - Taming the Beast
Maven - Taming the BeastMaven - Taming the Beast
Maven - Taming the BeastRoberto 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 ModernizationOrtus Solutions, Corp
 
FAST for SharePoint Deep Dive
FAST for SharePoint Deep DiveFAST for SharePoint Deep Dive
FAST for SharePoint Deep Diveneil_richards
 
ColdBox Hierarchical MVC - Transform Your Monolith
ColdBox Hierarchical MVC - Transform Your MonolithColdBox Hierarchical MVC - Transform Your Monolith
ColdBox Hierarchical MVC - Transform Your MonolithOrtus Solutions, Corp
 
Cakephp vs. laravel
Cakephp vs. laravelCakephp vs. laravel
Cakephp vs. laravelGirnarSoft
 
12 Factor Scala
12 Factor Scala12 Factor Scala
12 Factor ScalaJoe Kutner
 
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 infoSynapseindiappsdevelopment
 
Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design of Existing SoftwareSteven Smith
 
Saving Time By Testing With Jest
Saving Time By Testing With JestSaving Time By Testing With Jest
Saving Time By Testing With JestBen 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

Евгений Капинос "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 tipsosa_ora
 
JPA - Java Persistence API
JPA - Java Persistence APIJPA - Java Persistence API
JPA - Java Persistence APIThomas Wöhlke
 
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 StepGuo 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

Pivotal microservices spring_pcf_skillsmatter.pptx
Pivotal microservices spring_pcf_skillsmatter.pptxPivotal microservices spring_pcf_skillsmatter.pptx
Pivotal microservices spring_pcf_skillsmatter.pptxSufyaan Kazi
 
j2ee Building components
j2ee Building components j2ee Building components
j2ee Building components adeppathondur
 
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
TenYearsCPOptimizerPaulShawIBM
 
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 RDzSusan 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 2020Ieva 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 platformGrokking 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 slidesSusan Yoskin
 
NTTs Journey with Openstack-final
NTTs Journey with Openstack-finalNTTs Journey with Openstack-final
NTTs Journey with Openstack-finalshintaro mizuno
 
Request Cloud.pptx
Request Cloud.pptxRequest Cloud.pptx
Request Cloud.pptxFacultyofIT2
 
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 ProviderCA Technologies
 
How NBCUniversal Adopted DevOps
How NBCUniversal Adopted DevOpsHow NBCUniversal Adopted DevOps
How NBCUniversal Adopted DevOpsSanjeev 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 sdlcSkytap Cloud
 
Amazon CI/CD Practices for Software Development Teams - SRV320 - Chicago AWS ...
Amazon CI/CD Practices for Software Development Teams - SRV320 - Chicago AWS ...Amazon CI/CD Practices for Software Development Teams - SRV320 - Chicago AWS ...
Amazon CI/CD Practices for Software Development Teams - SRV320 - Chicago AWS ...Amazon Web Services
 

Similar to EJB 3.2/JPA 2.1 Best Practices (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
 
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
 
Amazon CI/CD Practices for Software Development Teams - SRV320 - Chicago AWS ...
Amazon CI/CD Practices for Software Development Teams - SRV320 - Chicago AWS ...Amazon CI/CD Practices for Software Development Teams - SRV320 - Chicago AWS ...
Amazon CI/CD Practices for Software Development Teams - SRV320 - Chicago AWS ...
 

Recently uploaded

SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdfSteve Caron
 
Business Analyzopedia - Your Pocket Gita for Business Analysis
Business Analyzopedia - Your Pocket Gita for Business AnalysisBusiness Analyzopedia - Your Pocket Gita for Business Analysis
Business Analyzopedia - Your Pocket Gita for Business AnalysisDEEPRAJ PATHAK
 
Effort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software ProjectsEffort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software ProjectsDEEPRAJ PATHAK
 
Transform your Corporate Strategy Office - Harness OnePlan’s Strategic Portfo...
Transform your Corporate Strategy Office - Harness OnePlan’s Strategic Portfo...Transform your Corporate Strategy Office - Harness OnePlan’s Strategic Portfo...
Transform your Corporate Strategy Office - Harness OnePlan’s Strategic Portfo...OnePlan Solutions
 
full course of software engineering mid term.pdf
full course of software engineering mid term.pdffull course of software engineering mid term.pdf
full course of software engineering mid term.pdfAbdul salam
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
The State of the Green IT at the beginning of 2024
The State of the Green IT at the beginning of 2024The State of the Green IT at the beginning of 2024
The State of the Green IT at the beginning of 2024Artur Skowroński
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
Explore the Three Main Types of Logistics - Inbound Logistics, Outbound Logis...
Explore the Three Main Types of Logistics - Inbound Logistics, Outbound Logis...Explore the Three Main Types of Logistics - Inbound Logistics, Outbound Logis...
Explore the Three Main Types of Logistics - Inbound Logistics, Outbound Logis...Piyovi
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
Revolutionize Your Video Editing with InVideo.io: A Comprehensive Review
Revolutionize Your Video Editing with InVideo.io: A Comprehensive ReviewRevolutionize Your Video Editing with InVideo.io: A Comprehensive Review
Revolutionize Your Video Editing with InVideo.io: A Comprehensive Reviewjw364beach
 
AmsterdamJUG April 2024 - Going serverless with Quarkus GraalVM native images...
AmsterdamJUG April 2024 - Going serverless with Quarkus GraalVM native images...AmsterdamJUG April 2024 - Going serverless with Quarkus GraalVM native images...
AmsterdamJUG April 2024 - Going serverless with Quarkus GraalVM native images...Bert Jan Schrijver
 
Key Steps in Agile Software Delivery Roadmap
Key Steps in Agile Software Delivery RoadmapKey Steps in Agile Software Delivery Roadmap
Key Steps in Agile Software Delivery RoadmapIshara Amarasekera
 
ETE PPT.pdf LMMKLMKLMLKMLLMJKBHJBHBNUIHBU
ETE PPT.pdf LMMKLMKLMLKMLLMJKBHJBHBNUIHBUETE PPT.pdf LMMKLMKLMLKMLLMJKBHJBHBNUIHBU
ETE PPT.pdf LMMKLMKLMLKMLLMJKBHJBHBNUIHBUsamruddhijedgule2004
 
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxUnderstanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxSasikiranMarri
 
What are the core components of Azure Data Engineer courses.docx
What are the core components of Azure Data Engineer courses.docxWhat are the core components of Azure Data Engineer courses.docx
What are the core components of Azure Data Engineer courses.docxkzayra69
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdfAndrey Devyatkin
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jNeo4j
 
Santander Stream Processing with Apache Flink
Santander Stream Processing with Apache FlinkSantander Stream Processing with Apache Flink
Santander Stream Processing with Apache Flinkconfluent
 

Recently uploaded (20)

SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
 
Business Analyzopedia - Your Pocket Gita for Business Analysis
Business Analyzopedia - Your Pocket Gita for Business AnalysisBusiness Analyzopedia - Your Pocket Gita for Business Analysis
Business Analyzopedia - Your Pocket Gita for Business Analysis
 
Effort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software ProjectsEffort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software Projects
 
Transform your Corporate Strategy Office - Harness OnePlan’s Strategic Portfo...
Transform your Corporate Strategy Office - Harness OnePlan’s Strategic Portfo...Transform your Corporate Strategy Office - Harness OnePlan’s Strategic Portfo...
Transform your Corporate Strategy Office - Harness OnePlan’s Strategic Portfo...
 
full course of software engineering mid term.pdf
full course of software engineering mid term.pdffull course of software engineering mid term.pdf
full course of software engineering mid term.pdf
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
The State of the Green IT at the beginning of 2024
The State of the Green IT at the beginning of 2024The State of the Green IT at the beginning of 2024
The State of the Green IT at the beginning of 2024
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Explore the Three Main Types of Logistics - Inbound Logistics, Outbound Logis...
Explore the Three Main Types of Logistics - Inbound Logistics, Outbound Logis...Explore the Three Main Types of Logistics - Inbound Logistics, Outbound Logis...
Explore the Three Main Types of Logistics - Inbound Logistics, Outbound Logis...
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
Revolutionize Your Video Editing with InVideo.io: A Comprehensive Review
Revolutionize Your Video Editing with InVideo.io: A Comprehensive ReviewRevolutionize Your Video Editing with InVideo.io: A Comprehensive Review
Revolutionize Your Video Editing with InVideo.io: A Comprehensive Review
 
AmsterdamJUG April 2024 - Going serverless with Quarkus GraalVM native images...
AmsterdamJUG April 2024 - Going serverless with Quarkus GraalVM native images...AmsterdamJUG April 2024 - Going serverless with Quarkus GraalVM native images...
AmsterdamJUG April 2024 - Going serverless with Quarkus GraalVM native images...
 
Key Steps in Agile Software Delivery Roadmap
Key Steps in Agile Software Delivery RoadmapKey Steps in Agile Software Delivery Roadmap
Key Steps in Agile Software Delivery Roadmap
 
ETE PPT.pdf LMMKLMKLMLKMLLMJKBHJBHBNUIHBU
ETE PPT.pdf LMMKLMKLMLKMLLMJKBHJBHBNUIHBUETE PPT.pdf LMMKLMKLMLKMLLMJKBHJBHBNUIHBU
ETE PPT.pdf LMMKLMKLMLKMLLMJKBHJBHBNUIHBU
 
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxUnderstanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
 
What are the core components of Azure Data Engineer courses.docx
What are the core components of Azure Data Engineer courses.docxWhat are the core components of Azure Data Engineer courses.docx
What are the core components of Azure Data Engineer courses.docx
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
 
Santander Stream Processing with Apache Flink
Santander Stream Processing with Apache FlinkSantander Stream Processing with Apache Flink
Santander Stream Processing with Apache Flink
 

EJB 3.2/JPA 2.1 Best Practices

  • 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