SlideShare une entreprise Scribd logo
1  sur  13
Caching is widely used for optimizing database applications. A cache is designed to reduce traffic between your application and the database by conserving data already loaded from the database.  Database access is necessary only when retrieving data that is not currently available in the cache.  The application may need to empty (invalidate) the cache from time to time if the database is updated or modified in some way, because it has no way of knowing whether the cache is up to date
Hibernate uses two different caches for objects: first-level cache and second-level cache.  First-level cache is associated with the Session object, while second-level cache is associated with the Session Factory object  By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction.  For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications.
To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions.  These objects are available to the whole application, not just to the user running the query.  This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided.
Caches are complicated pieces of software, and the market offers quite a number of choices, both open source and commercial. Hibernate supports the following open-source cache implementations out-of-the-box:  EHCache  (org.hibernate.cache.EhCacheProvider)  OSCache  (org.hibernate.cache.OSCacheProvider)  SwarmCache  (org.hibernate.cache.SwarmCacheProvider)  JBoss TreeCache  (org.hibernate.cache.TreeCacheProvider
Each cache provides different capacities in terms of performance, memory use, and configuration possibilities:  EHCache  is a fast, lightweight, and easy-to-use in-process cache. It supports read-only and read/write caching, and memory- and disk-based caching. However, it does not support clustering.  OSCache  is another open-source caching solution. It is part of a larger package, which also provides caching functionalities for JSP pages or arbitrary objects. It is a powerful and flexible package, which, like EHCache, supports read-only and read/write caching, and memory- and disk-based caching. It also provides basic support for clustering via either JavaGroups or JMS.
SwarmCache  is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching (the next section explains this term). This type of cache is appropriate for applications that typically have many more read operations than write operations.  JBoss   TreeCache  is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture
Caching Strategies Once you have chosen your cache implementation, you need to specify your access strategies. The following four caching strategies are available:  Read-only: This strategy is useful for data that is read frequently but never updated. This is by far the simplest and best-performing cache strategy.  Read/write: Read/write caches may be appropriate if your data needs to be updated. They carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when Session.close() or Session.disconnect() is called.  Nonstrict read/write: This strategy does not guarantee that two transactions won't simultaneously modify the same data. Therefore, it may be most appropriate for data that is read often but only occasionally modified.  Transactional: This is a fully transactional cache that may be used only in a JTA environment.
Cache Configuration To activate second-level caching, you need to define the hibernate.cache.provider_class property in the hibernate.cfg.xml file as follows:  <hibernate-configuration>  <session-factory>  ...  <property name=&quot;hibernate.cache.provider_class&quot;> org.hibernate.cache.EHCacheProvider  </property> ...  </session-factory>  </hibernate-configuration>
You can activate second-level caching classes in one of the two following ways:  1. You activate it on a class-by-class basis in the *.hbm.xml file, using the cache attribute: <hibernate-mapping  package=&quot;com.wakaleo.articles.caching.businessobjects&quot;> <class name=&quot;Country&quot; table=&quot;COUNTRY&quot; dynamic-update=&quot;true&quot;>  <meta attribute=&quot;implement-equals&quot;>true</meta> <cache usage=&quot;read-only&quot;/>   ... </class> </hibernate-mapping>
2.  You can store all cache information in the hibernate.cfg.xml file, using the class-cache attribute:  <hibernate-configuration> <session-factory>  ...  <property name=&quot;hibernate.cache.provider_class&quot;> org.hibernate.cache.EHCacheProvider </property>  ...  <class-cache class=&quot;com.wakaleo.articles.caching.businessobjects.Country&quot; usage=&quot;read-only&quot; />  </session-factory> </hibernate-configuration>
Next, you need to configure the cache rules for this class. you can use the following simple EHCache configuration file:  <ehcache>  <diskStore path=&quot;java.io.tmpdir&quot;/> <defaultCache  maxElementsInMemory=&quot;10000&quot;  eternal=&quot;false“ timeToIdleSeconds=&quot;120“ timeToLiveSeconds=&quot;120&quot;  overflowToDisk=&quot;true“ diskPersistent=&quot;false“ diskExpiryThreadIntervalSeconds=&quot;120&quot; memoryStoreEvictionPolicy=&quot;LRU&quot; /> <cache name=&quot;com.wakaleo.articles.caching.businessobjects.Country&quot; maxElementsInMemory=&quot;300“ eternal=&quot;true&quot;  overflowToDisk=&quot;false&quot; />  </ehcache>
Using Query Caches In certain cases, it is useful to cache the exact results of a query, not just certain objects.  To do this, you need to set the hibernate.cache.use_query_cache property in the hibernate.cfg.xml file to true, as follows:  <property name=&quot;hibernate.cache.use_query_cache&quot;>true</property>
Then, you use the setCacheable() method as follows on any query you wish to cache:  public class CountryDAO {  public List getCountries()  { return SessionManager.currentSession() .createQuery(&quot;from Country as c order by c.name&quot;)  .setCacheable(true)  .list(); } }

Contenu connexe

Tendances

Tendances (8)

Oracle Complete Interview Questions
Oracle Complete Interview QuestionsOracle Complete Interview Questions
Oracle Complete Interview Questions
 
Fard Solutions Sdn Bhd
Fard Solutions Sdn Bhd Fard Solutions Sdn Bhd
Fard Solutions Sdn Bhd
 
No SQL and MongoDB - Hyderabad Scalability Meetup
No SQL and MongoDB - Hyderabad Scalability MeetupNo SQL and MongoDB - Hyderabad Scalability Meetup
No SQL and MongoDB - Hyderabad Scalability Meetup
 
Lecture12
Lecture12Lecture12
Lecture12
 
Understanding and building big data Architectures - NoSQL
Understanding and building big data Architectures - NoSQLUnderstanding and building big data Architectures - NoSQL
Understanding and building big data Architectures - NoSQL
 
MySQL Cluster Schema management (2014)
MySQL Cluster Schema management (2014)MySQL Cluster Schema management (2014)
MySQL Cluster Schema management (2014)
 
Parallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDBParallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDB
 
Microsoft azure database offerings
Microsoft azure database offeringsMicrosoft azure database offerings
Microsoft azure database offerings
 

Similaire à 10 Cache Implementation

Caching for J2ee Enterprise Applications
Caching for J2ee Enterprise ApplicationsCaching for J2ee Enterprise Applications
Caching for J2ee Enterprise Applications
Debajani Mohanty
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jj
Joe Jacob
 
nHibernate Caching
nHibernate CachingnHibernate Caching
nHibernate Caching
Guo Albert
 
Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate Notes
Kaniska Mandal
 

Similaire à 10 Cache Implementation (20)

Caching for J2ee Enterprise Applications
Caching for J2ee Enterprise ApplicationsCaching for J2ee Enterprise Applications
Caching for J2ee Enterprise Applications
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jj
 
Academy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storageAcademy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storage
 
Html5 cache mechanism & local storage
Html5 cache mechanism & local storageHtml5 cache mechanism & local storage
Html5 cache mechanism & local storage
 
11g r2 flashcache_Tips
11g r2 flashcache_Tips11g r2 flashcache_Tips
11g r2 flashcache_Tips
 
nHibernate Caching
nHibernate CachingnHibernate Caching
nHibernate Caching
 
Caching By Nyros Developer
Caching By Nyros DeveloperCaching By Nyros Developer
Caching By Nyros Developer
 
Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate Notes
 
Chapter 23
Chapter 23Chapter 23
Chapter 23
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
 
your browser, my storage
your browser, my storageyour browser, my storage
your browser, my storage
 
Containers and Databases
Containers and DatabasesContainers and Databases
Containers and Databases
 
Caching in Kentico 11
Caching in Kentico 11Caching in Kentico 11
Caching in Kentico 11
 
Scaling PHP apps
Scaling PHP appsScaling PHP apps
Scaling PHP apps
 
Caching technology comparison
Caching technology comparisonCaching technology comparison
Caching technology comparison
 
Developing High Performance and Scalable ColdFusion Application Using Terraco...
Developing High Performance and Scalable ColdFusion Application Using Terraco...Developing High Performance and Scalable ColdFusion Application Using Terraco...
Developing High Performance and Scalable ColdFusion Application Using Terraco...
 
Developing High Performance and Scalable ColdFusion Applications Using Terrac...
Developing High Performance and Scalable ColdFusion Applications Using Terrac...Developing High Performance and Scalable ColdFusion Applications Using Terrac...
Developing High Performance and Scalable ColdFusion Applications Using Terrac...
 
White Paper: EMC FAST Cache — A Detailed Review
White Paper: EMC FAST Cache — A Detailed Review   White Paper: EMC FAST Cache — A Detailed Review
White Paper: EMC FAST Cache — A Detailed Review
 
Spring One 2 GX 2014 - CACHING WITH SPRING: ADVANCED TOPICS AND BEST PRACTICES
Spring One 2 GX 2014 - CACHING WITH SPRING: ADVANCED TOPICS AND BEST PRACTICESSpring One 2 GX 2014 - CACHING WITH SPRING: ADVANCED TOPICS AND BEST PRACTICES
Spring One 2 GX 2014 - CACHING WITH SPRING: ADVANCED TOPICS AND BEST PRACTICES
 
Caching in drupal
Caching in drupalCaching in drupal
Caching in drupal
 

Plus de Ranjan Kumar (20)

Introduction to java ee
Introduction to java eeIntroduction to java ee
Introduction to java ee
 
Fantastic life views ons
Fantastic life views  onsFantastic life views  ons
Fantastic life views ons
 
Lessons on Life
Lessons on LifeLessons on Life
Lessons on Life
 
Story does not End here
Story does not End hereStory does not End here
Story does not End here
 
Whata Split Second Looks Like
Whata Split Second Looks LikeWhata Split Second Looks Like
Whata Split Second Looks Like
 
Friendship so Sweet
Friendship so SweetFriendship so Sweet
Friendship so Sweet
 
Dedicate Time
Dedicate TimeDedicate Time
Dedicate Time
 
Paradise on Earth
Paradise on EarthParadise on Earth
Paradise on Earth
 
Bolivian Highway
Bolivian HighwayBolivian Highway
Bolivian Highway
 
Chinese Proverb
Chinese ProverbChinese Proverb
Chinese Proverb
 
Warren Buffet
Warren BuffetWarren Buffet
Warren Buffet
 
Dear Son Dear Daughter
Dear Son Dear DaughterDear Son Dear Daughter
Dear Son Dear Daughter
 
Jara Sochiye
Jara SochiyeJara Sochiye
Jara Sochiye
 
Blue Beauty
Blue BeautyBlue Beauty
Blue Beauty
 
Alaska Railway Routes
Alaska Railway RoutesAlaska Railway Routes
Alaska Railway Routes
 
Poison that Kills the Dreams
Poison that Kills the DreamsPoison that Kills the Dreams
Poison that Kills the Dreams
 
Horrible Jobs
Horrible JobsHorrible Jobs
Horrible Jobs
 
Best Aviation Photography
Best Aviation PhotographyBest Aviation Photography
Best Aviation Photography
 
Role of Attitude
Role of AttitudeRole of Attitude
Role of Attitude
 
45 Lesons in Life
45 Lesons in Life45 Lesons in Life
45 Lesons in Life
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

10 Cache Implementation

  • 1. Caching is widely used for optimizing database applications. A cache is designed to reduce traffic between your application and the database by conserving data already loaded from the database. Database access is necessary only when retrieving data that is not currently available in the cache. The application may need to empty (invalidate) the cache from time to time if the database is updated or modified in some way, because it has no way of knowing whether the cache is up to date
  • 2. Hibernate uses two different caches for objects: first-level cache and second-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the Session Factory object By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications.
  • 3. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided.
  • 4. Caches are complicated pieces of software, and the market offers quite a number of choices, both open source and commercial. Hibernate supports the following open-source cache implementations out-of-the-box: EHCache (org.hibernate.cache.EhCacheProvider) OSCache (org.hibernate.cache.OSCacheProvider) SwarmCache (org.hibernate.cache.SwarmCacheProvider) JBoss TreeCache (org.hibernate.cache.TreeCacheProvider
  • 5. Each cache provides different capacities in terms of performance, memory use, and configuration possibilities: EHCache is a fast, lightweight, and easy-to-use in-process cache. It supports read-only and read/write caching, and memory- and disk-based caching. However, it does not support clustering. OSCache is another open-source caching solution. It is part of a larger package, which also provides caching functionalities for JSP pages or arbitrary objects. It is a powerful and flexible package, which, like EHCache, supports read-only and read/write caching, and memory- and disk-based caching. It also provides basic support for clustering via either JavaGroups or JMS.
  • 6. SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching (the next section explains this term). This type of cache is appropriate for applications that typically have many more read operations than write operations. JBoss TreeCache is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture
  • 7. Caching Strategies Once you have chosen your cache implementation, you need to specify your access strategies. The following four caching strategies are available: Read-only: This strategy is useful for data that is read frequently but never updated. This is by far the simplest and best-performing cache strategy. Read/write: Read/write caches may be appropriate if your data needs to be updated. They carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when Session.close() or Session.disconnect() is called. Nonstrict read/write: This strategy does not guarantee that two transactions won't simultaneously modify the same data. Therefore, it may be most appropriate for data that is read often but only occasionally modified. Transactional: This is a fully transactional cache that may be used only in a JTA environment.
  • 8. Cache Configuration To activate second-level caching, you need to define the hibernate.cache.provider_class property in the hibernate.cfg.xml file as follows: <hibernate-configuration> <session-factory> ... <property name=&quot;hibernate.cache.provider_class&quot;> org.hibernate.cache.EHCacheProvider </property> ... </session-factory> </hibernate-configuration>
  • 9. You can activate second-level caching classes in one of the two following ways: 1. You activate it on a class-by-class basis in the *.hbm.xml file, using the cache attribute: <hibernate-mapping package=&quot;com.wakaleo.articles.caching.businessobjects&quot;> <class name=&quot;Country&quot; table=&quot;COUNTRY&quot; dynamic-update=&quot;true&quot;> <meta attribute=&quot;implement-equals&quot;>true</meta> <cache usage=&quot;read-only&quot;/> ... </class> </hibernate-mapping>
  • 10. 2. You can store all cache information in the hibernate.cfg.xml file, using the class-cache attribute: <hibernate-configuration> <session-factory> ... <property name=&quot;hibernate.cache.provider_class&quot;> org.hibernate.cache.EHCacheProvider </property> ... <class-cache class=&quot;com.wakaleo.articles.caching.businessobjects.Country&quot; usage=&quot;read-only&quot; /> </session-factory> </hibernate-configuration>
  • 11. Next, you need to configure the cache rules for this class. you can use the following simple EHCache configuration file: <ehcache> <diskStore path=&quot;java.io.tmpdir&quot;/> <defaultCache maxElementsInMemory=&quot;10000&quot; eternal=&quot;false“ timeToIdleSeconds=&quot;120“ timeToLiveSeconds=&quot;120&quot; overflowToDisk=&quot;true“ diskPersistent=&quot;false“ diskExpiryThreadIntervalSeconds=&quot;120&quot; memoryStoreEvictionPolicy=&quot;LRU&quot; /> <cache name=&quot;com.wakaleo.articles.caching.businessobjects.Country&quot; maxElementsInMemory=&quot;300“ eternal=&quot;true&quot; overflowToDisk=&quot;false&quot; /> </ehcache>
  • 12. Using Query Caches In certain cases, it is useful to cache the exact results of a query, not just certain objects. To do this, you need to set the hibernate.cache.use_query_cache property in the hibernate.cfg.xml file to true, as follows: <property name=&quot;hibernate.cache.use_query_cache&quot;>true</property>
  • 13. Then, you use the setCacheable() method as follows on any query you wish to cache: public class CountryDAO { public List getCountries() { return SessionManager.currentSession() .createQuery(&quot;from Country as c order by c.name&quot;) .setCacheable(true) .list(); } }