Performance Tips and Tricks: Java EE, Java Persistence API and JavaServer Faces

Dr. Spock
Dr. SpockSenior Software Architect at SpockNET
Performance Tips and Tricks: Java
  EE, Java Persistence API, and
        JavaServer Faces
Alberto Lemos (Dr. Spock)    Danival Taffarel Calegari
 Senior Software Architect   MATERA Systems Architect
   Globalcode Instructor       Globalcode Instructor




                                       Globalcode – Open4education
Agenda
 Motivation
 Data recovery strategies
   Lazy vs Eager
   Cache
 Web UI Design Strategies
   Conversation Scope
   View Helper + Persistence Service
   Lazy UI Components



                                       Globalcode – Open4education
Objective




  “Present some tips and tricks on web
application development with JSF, Ajax,
               and JPA”



                             Globalcode – Open4education
Motivation
 JavaServer Faces (JSF) is a paradigm change in
 Web development with Java EE;
 It establishes a model for web UI components.
 JSF evolved!
   JSF 1.x (without AJAX) => Ineffective event oriented
   JSF 1.x + AJAX lib => Event oriented
   JSF 2.x => Event oriented
 It's necessary to evolve the development
 techniques on presentation and persistence layers!

                                            Globalcode – Open4education
Agenda
 Motivation
 Data recovery strategies
   Lazy vs Eager
   Cache
 Web UI Design Strategies
   Conversation Scope
   View Helper + Persistence Service
   Lazy UI Components



                                       Globalcode – Open4education
Lazy vs Eager
 Strategies to handle the entity relationships;
 Lazy: it fetches data on demand;
 Eager: it always fetches data.




                                        Globalcode – Open4education
Lazy vs Eager
 Tip: JPA allows for a change from lazy to eager
 using the JP-QL;
   select distinct c from Categoria c join fetch c.produtos
 It runs only one SELECT in the database;
 Join fetch solves the N+1 problem;
 Distinct should be used to avoid duplicated
 results;
 Note: this may cause problems with database
 pagination.

                                            Globalcode – Open4education
Lazy vs Eager
 Tip: Try to paginate in database using lazy
 strategy;
   Use the setFirstResult and setMaxResults methods by
   Query.
 The JPA provider will use native database
 commands to limit the query results;
 Beware: join fetch for 1:N relationships causes
 performance and memory problems.
   WARN: firstResult/maxResults specified with collection
   fetch; applying in memory!

                                           Globalcode – Open4education
Lazy vs Eager
 Tip: Try to use eager whenever bulk processing
 data;
   One common situation is report generation.
 Be careful with memory use;
   Do a previous query to get the ids and limit the results
   with an in clause;
   Use the clear method from EntityManager to remove
   processed objects from memory.




                                             Globalcode – Open4education
Cache
 First level cache
   While the EntityManager is open, it maitains the
   references for all objects loaded by it;
   This cache is erased when the clear method is called.
 Second level cache
   Maintains object references per EntityManagerFactory;
   It is a per-application cache.




                                           Globalcode – Open4education
Cache




        Globalcode – Open4education
Cache
 Trick: By loading related entities into first level
 cache before the main query, performance will
 be greatly improved.
   It can only work with N:1 relationships for entities with a
   small number of instances.
 Example: Fetching products with any filter.
   If there are 200 categories, the lazy strategy should run
   200 queries on the category table;
   Execute a “select c from Category c” before querying for
   products.


                                               Globalcode – Open4education
Cache
 Tip: Use second level cache to save memory
 and to improve performance;
 Choose non-frequent altered entities;
 If an external application changes the database,
 data in the second level cache will become
 outdated.
   Apply a time limit for data expiration.




                                             Globalcode – Open4education
Agenda
 Motivation
 Data recovery strategies
   Lazy vs Eager
   Cache
 Web UI Design Strategies
   Conversation Scope
   View Helper + Persistence Service
   Lazy UI Components



                                       Globalcode – Open4education
The Problem
 DAO + JDBC => open/close connection;
 DAO + Persistence Context => open/close session;




 LazyInitializationException!
                                   Globalcode – Open4education
Old Solution
  OpenSessionInViewFilter Design Pattern;




  New problems!

                                   Globalcode – Open4education
New Problems
 OpenSessionInViewFilter Design Pattern;




 1st REQUEST        2nd REQUEST        Nth REQUEST


 Each request uses a different persistence context;
 Session scoped entities can throw
 LazyInitializationException!

                                      Globalcode – Open4education
Web 1.0
 Request-oriented web applications;




                                      Globalcode – Open4education
Web 2.0
 AJAX-oriented web applications;




                                   Globalcode – Open4education
Web UI Strategies
 Tip: Use the view and conversation scopes;
   Avoid to use the session scope for objects with short
   lifetime;
   Usually the lifetime is managed by the container through
   settings (Annotations or XML);




                                            Globalcode – Open4education
Web UI Strategies
 Tip: Store the persistence context into the view
 scope or conversation scope;
   The EntityManager remains open for a specified time;




                                          Globalcode – Open4education
Web UI Strategies
 Tip: Store the persistence context into the view
 scope or conversation scope;
   The EntityManager remains open for a specified time;
   Enables the 1st level cache;
   Prevents the LazyInitializationException errors;
   Enables paging in the presentation tier Integrated with
   the persistence tier;
   Attention: The 1st level cache can increase for a long
   term conversation scope.



                                             Globalcode – Open4education
Web UI Strategies
 Tip: Integrate the View Helper (pattern) with the
 persistence service (JPA);
   Implement a List (from Collections API) that receives a
   Query object (from JPA);
   Implement a DataModel (from JSF API) that receives a
   Query object;
   Implement an ExtendedTableDataModel (from
   Richfaces API) that receives an EntityManager object;
   Pagination: Use setFirtResult() and setMaxResults().
   Be careful with eager fetching!
   Filter and order by: Use CriteriaBuilder object (from
   JPA).

                                           Globalcode – Open4education
Web UI Strategies
 Tip: Use UI Components that supports “lazy
 loading” via Ajax;




                                   Globalcode – Open4education
Web UI Strategies
 Tip: Use UI Components that supports “lazy
 loading” via Ajax;




                                   Globalcode – Open4education
Web UI Strategies
 Tip: Use UI Components that supports “lazy
 loading” via Ajax;




                                   Globalcode – Open4education
Sample Application
 The tips and tricks are demonstrated by a sample
 application;
 It is avaliable to donwload at:
 http://sourceforge.net/projects/j1catalogproto2/




                                    Globalcode – Open4education
Thank you!

Alberto Lemos (Dr. Spock)       Danival Taffarel Calegari
http://www.globalcode.com.br/   http://www.matera.com/
spock@globalcode.com.br         danival@globalcode.com.br
http://twitter.com/drspockbr    http://twitter.com/danivaltc




                                             Globalcode – Open4education
1 of 28

More Related Content

Similar to Performance Tips and Tricks: Java EE, Java Persistence API and JavaServer Faces

GraphQL AdvancedGraphQL Advanced
GraphQL AdvancedLeanIX GmbH
1.2K views44 slides
sample1sample1
sample1sudipta nandi
150 views4 slides
KiranGara_JEE_7YrsKiranGara_JEE_7Yrs
KiranGara_JEE_7YrsKiran Gara
162 views8 slides

Similar to Performance Tips and Tricks: Java EE, Java Persistence API and JavaServer Faces(20)

GraphQL AdvancedGraphQL Advanced
GraphQL Advanced
LeanIX GmbH1.2K views
sample1sample1
sample1
sudipta nandi150 views
JDK 8 and JDK 8 Updates in OpenJDKJDK 8 and JDK 8 Updates in OpenJDK
JDK 8 and JDK 8 Updates in OpenJDK
Wolfgang Weigend2.5K views
KiranGara_JEE_7YrsKiranGara_JEE_7Yrs
KiranGara_JEE_7Yrs
Kiran Gara162 views
ResumeResume
Resume
anil chowdhary159 views
Rishabha singhcvRishabha singhcv
Rishabha singhcv
Rishabha Singh63 views
Opendaylight SDN ControllerOpendaylight SDN Controller
Opendaylight SDN Controller
Sumit Arora26.4K views
Building and managing applications fast for IBM iBuilding and managing applications fast for IBM i
Building and managing applications fast for IBM i
Zend by Rogue Wave Software160 views
Cakephp manual-11Cakephp manual-11
Cakephp manual-11
Aditya Pandey8.4K views
Bala  Sr Java DeveloperBala  Sr Java Developer
Bala Sr Java Developer
Java Dev344 views
Vue.js Use CasesVue.js Use Cases
Vue.js Use Cases
GlobalLogic Ukraine3.9K views
Getting Started with SeleniumGetting Started with Selenium
Getting Started with Selenium
Dave Haeffner2K views
Krishnagopal Thogiti_JavaKrishnagopal Thogiti_Java
Krishnagopal Thogiti_Java
Krishnagopal Thogiti447 views
Raghava_KumariRaghava_Kumari
Raghava_Kumari
raghava kumari129 views
CodeceptionCodeception
Codeception
少東 張3.7K views

More from Dr. Spock(20)

TDC2011: Spring MobileTDC2011: Spring Mobile
TDC2011: Spring Mobile
Dr. Spock628 views
TDC2011: Java EE 6 & AzureTDC2011: Java EE 6 & Azure
TDC2011: Java EE 6 & Azure
Dr. Spock513 views

Recently uploaded(20)

[2023] Putting the R! in R&D.pdf[2023] Putting the R! in R&D.pdf
[2023] Putting the R! in R&D.pdf
Eleanor McHugh36 views
The Research Portal of Catalonia: Growing more (information) & more (services)The Research Portal of Catalonia: Growing more (information) & more (services)
The Research Portal of Catalonia: Growing more (information) & more (services)
CSUC - Consorci de Serveis Universitaris de Catalunya59 views
Web Dev - 1 PPT.pdfWeb Dev - 1 PPT.pdf
Web Dev - 1 PPT.pdf
gdsczhcet49 views

Performance Tips and Tricks: Java EE, Java Persistence API and JavaServer Faces

  • 1. Performance Tips and Tricks: Java EE, Java Persistence API, and JavaServer Faces Alberto Lemos (Dr. Spock) Danival Taffarel Calegari Senior Software Architect MATERA Systems Architect Globalcode Instructor Globalcode Instructor Globalcode – Open4education
  • 2. Agenda Motivation Data recovery strategies Lazy vs Eager Cache Web UI Design Strategies Conversation Scope View Helper + Persistence Service Lazy UI Components Globalcode – Open4education
  • 3. Objective “Present some tips and tricks on web application development with JSF, Ajax, and JPA” Globalcode – Open4education
  • 4. Motivation JavaServer Faces (JSF) is a paradigm change in Web development with Java EE; It establishes a model for web UI components. JSF evolved! JSF 1.x (without AJAX) => Ineffective event oriented JSF 1.x + AJAX lib => Event oriented JSF 2.x => Event oriented It's necessary to evolve the development techniques on presentation and persistence layers! Globalcode – Open4education
  • 5. Agenda Motivation Data recovery strategies Lazy vs Eager Cache Web UI Design Strategies Conversation Scope View Helper + Persistence Service Lazy UI Components Globalcode – Open4education
  • 6. Lazy vs Eager Strategies to handle the entity relationships; Lazy: it fetches data on demand; Eager: it always fetches data. Globalcode – Open4education
  • 7. Lazy vs Eager Tip: JPA allows for a change from lazy to eager using the JP-QL; select distinct c from Categoria c join fetch c.produtos It runs only one SELECT in the database; Join fetch solves the N+1 problem; Distinct should be used to avoid duplicated results; Note: this may cause problems with database pagination. Globalcode – Open4education
  • 8. Lazy vs Eager Tip: Try to paginate in database using lazy strategy; Use the setFirstResult and setMaxResults methods by Query. The JPA provider will use native database commands to limit the query results; Beware: join fetch for 1:N relationships causes performance and memory problems. WARN: firstResult/maxResults specified with collection fetch; applying in memory! Globalcode – Open4education
  • 9. Lazy vs Eager Tip: Try to use eager whenever bulk processing data; One common situation is report generation. Be careful with memory use; Do a previous query to get the ids and limit the results with an in clause; Use the clear method from EntityManager to remove processed objects from memory. Globalcode – Open4education
  • 10. Cache First level cache While the EntityManager is open, it maitains the references for all objects loaded by it; This cache is erased when the clear method is called. Second level cache Maintains object references per EntityManagerFactory; It is a per-application cache. Globalcode – Open4education
  • 11. Cache Globalcode – Open4education
  • 12. Cache Trick: By loading related entities into first level cache before the main query, performance will be greatly improved. It can only work with N:1 relationships for entities with a small number of instances. Example: Fetching products with any filter. If there are 200 categories, the lazy strategy should run 200 queries on the category table; Execute a “select c from Category c” before querying for products. Globalcode – Open4education
  • 13. Cache Tip: Use second level cache to save memory and to improve performance; Choose non-frequent altered entities; If an external application changes the database, data in the second level cache will become outdated. Apply a time limit for data expiration. Globalcode – Open4education
  • 14. Agenda Motivation Data recovery strategies Lazy vs Eager Cache Web UI Design Strategies Conversation Scope View Helper + Persistence Service Lazy UI Components Globalcode – Open4education
  • 15. The Problem DAO + JDBC => open/close connection; DAO + Persistence Context => open/close session; LazyInitializationException! Globalcode – Open4education
  • 16. Old Solution OpenSessionInViewFilter Design Pattern; New problems! Globalcode – Open4education
  • 17. New Problems OpenSessionInViewFilter Design Pattern; 1st REQUEST 2nd REQUEST Nth REQUEST Each request uses a different persistence context; Session scoped entities can throw LazyInitializationException! Globalcode – Open4education
  • 18. Web 1.0 Request-oriented web applications; Globalcode – Open4education
  • 19. Web 2.0 AJAX-oriented web applications; Globalcode – Open4education
  • 20. Web UI Strategies Tip: Use the view and conversation scopes; Avoid to use the session scope for objects with short lifetime; Usually the lifetime is managed by the container through settings (Annotations or XML); Globalcode – Open4education
  • 21. Web UI Strategies Tip: Store the persistence context into the view scope or conversation scope; The EntityManager remains open for a specified time; Globalcode – Open4education
  • 22. Web UI Strategies Tip: Store the persistence context into the view scope or conversation scope; The EntityManager remains open for a specified time; Enables the 1st level cache; Prevents the LazyInitializationException errors; Enables paging in the presentation tier Integrated with the persistence tier; Attention: The 1st level cache can increase for a long term conversation scope. Globalcode – Open4education
  • 23. Web UI Strategies Tip: Integrate the View Helper (pattern) with the persistence service (JPA); Implement a List (from Collections API) that receives a Query object (from JPA); Implement a DataModel (from JSF API) that receives a Query object; Implement an ExtendedTableDataModel (from Richfaces API) that receives an EntityManager object; Pagination: Use setFirtResult() and setMaxResults(). Be careful with eager fetching! Filter and order by: Use CriteriaBuilder object (from JPA). Globalcode – Open4education
  • 24. Web UI Strategies Tip: Use UI Components that supports “lazy loading” via Ajax; Globalcode – Open4education
  • 25. Web UI Strategies Tip: Use UI Components that supports “lazy loading” via Ajax; Globalcode – Open4education
  • 26. Web UI Strategies Tip: Use UI Components that supports “lazy loading” via Ajax; Globalcode – Open4education
  • 27. Sample Application The tips and tricks are demonstrated by a sample application; It is avaliable to donwload at: http://sourceforge.net/projects/j1catalogproto2/ Globalcode – Open4education
  • 28. Thank you! Alberto Lemos (Dr. Spock) Danival Taffarel Calegari http://www.globalcode.com.br/ http://www.matera.com/ spock@globalcode.com.br danival@globalcode.com.br http://twitter.com/drspockbr http://twitter.com/danivaltc Globalcode – Open4education