SlideShare una empresa de 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(); } }

Más contenido relacionado

La actualidad más candente

La actualidad más candente (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
 

Similar 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
 

Similar 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
 

Más 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
 

Más 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

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Último (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

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