SlideShare uma empresa Scribd logo
1 de 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(); } }

Mais conteúdo relacionado

Mais procurados

Mais procurados (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
 

Semelhante a 10 Cache Implementation

Caching for J2ee Enterprise Applications
Caching for J2ee Enterprise ApplicationsCaching for J2ee Enterprise Applications
Caching for J2ee Enterprise ApplicationsDebajani Mohanty
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jjJoe Jacob
 
Academy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storageAcademy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storageBinary Studio
 
Html5 cache mechanism & local storage
Html5 cache mechanism & local storageHtml5 cache mechanism & local storage
Html5 cache mechanism & local storageSendhil Kumar Kannan
 
11g r2 flashcache_Tips
11g r2 flashcache_Tips11g r2 flashcache_Tips
11g r2 flashcache_TipsLouis liu
 
nHibernate Caching
nHibernate CachingnHibernate Caching
nHibernate CachingGuo Albert
 
Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate NotesKaniska Mandal
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginnersRahul Jain
 
Containers and Databases
Containers and DatabasesContainers and Databases
Containers and DatabasesFernando Ike
 
Caching technology comparison
Caching technology comparisonCaching technology comparison
Caching technology comparisonRohit Kelapure
 
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...ColdFusionConference
 
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...Shailendra Prasad
 
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 EMC
 
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 PRACTICESMichael Plöd
 

Semelhante a 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
 

Mais de Ranjan Kumar

Introduction to java ee
Introduction to java eeIntroduction to java ee
Introduction to java eeRanjan Kumar
 
Fantastic life views ons
Fantastic life views  onsFantastic life views  ons
Fantastic life views onsRanjan Kumar
 
Story does not End here
Story does not End hereStory does not End here
Story does not End hereRanjan Kumar
 
Whata Split Second Looks Like
Whata Split Second Looks LikeWhata Split Second Looks Like
Whata Split Second Looks LikeRanjan Kumar
 
Friendship so Sweet
Friendship so SweetFriendship so Sweet
Friendship so SweetRanjan Kumar
 
Dear Son Dear Daughter
Dear Son Dear DaughterDear Son Dear Daughter
Dear Son Dear DaughterRanjan Kumar
 
Alaska Railway Routes
Alaska Railway RoutesAlaska Railway Routes
Alaska Railway RoutesRanjan Kumar
 
Poison that Kills the Dreams
Poison that Kills the DreamsPoison that Kills the Dreams
Poison that Kills the DreamsRanjan Kumar
 
Best Aviation Photography
Best Aviation PhotographyBest Aviation Photography
Best Aviation PhotographyRanjan Kumar
 

Mais 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
 

Último

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 FresherRemote DBA Services
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
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 Takeoffsammart93
 
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.pptxRustici Software
 
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, ...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 

Último (20)

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 New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
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
 
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, ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

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(); } }