SlideShare a Scribd company logo
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(); } }

More Related Content

What's hot (8)

DOC
Oracle Complete Interview Questions
Sandeep Sharma IIMK Smart City,IoT,Bigdata,Cloud,BI,DW
 
PPTX
Fard Solutions Sdn Bhd
Hamid J. Fard
 
PPT
No SQL and MongoDB - Hyderabad Scalability Meetup
Hyderabad Scalability Meetup
 
PPT
Lecture12
Châu Thanh Chương
 
PDF
Understanding and building big data Architectures - NoSQL
Hyderabad Scalability Meetup
 
PDF
MySQL Cluster Schema management (2014)
Frazer Clement
 
PDF
Parallel Replication in MySQL and MariaDB
Mydbops
 
PPTX
Microsoft azure database offerings
Guruprasad Vijayarao
 
Oracle Complete Interview Questions
Sandeep Sharma IIMK Smart City,IoT,Bigdata,Cloud,BI,DW
 
Fard Solutions Sdn Bhd
Hamid J. Fard
 
No SQL and MongoDB - Hyderabad Scalability Meetup
Hyderabad Scalability Meetup
 
Understanding and building big data Architectures - NoSQL
Hyderabad Scalability Meetup
 
MySQL Cluster Schema management (2014)
Frazer Clement
 
Parallel Replication in MySQL and MariaDB
Mydbops
 
Microsoft azure database offerings
Guruprasad Vijayarao
 

Similar to 10 Cache Implementation (20)

PPT
Caching for J2ee Enterprise Applications
Debajani Mohanty
 
PDF
Best_Practices_for_Managing_Your_Artifactory_Filestore-2.pdf
YoramSamoray2
 
PPT
Hibernate jj
Joe Jacob
 
PPTX
Academy PRO: HTML5 Data storage
Binary Studio
 
PPTX
Html5 cache mechanism & local storage
Sendhil Kumar Kannan
 
PDF
11g r2 flashcache_Tips
Louis liu
 
PPTX
nHibernate Caching
Guo Albert
 
PPT
Caching By Nyros Developer
Nyros Technologies
 
DOC
Advanced Hibernate Notes
Kaniska Mandal
 
PPTX
Chapter 23
application developer
 
DOC
Hibernate tutorial for beginners
Rahul Jain
 
PDF
your browser, my storage
Francesco Fullone
 
PDF
Containers and Databases
Fernando Ike
 
PPTX
Caching in Kentico 11
Christopher Bass
 
PDF
Scaling PHP apps
Matteo Moretti
 
ODP
Caching technology comparison
Rohit Kelapure
 
PDF
Developing High Performance and Scalable ColdFusion Application Using Terraco...
ColdFusionConference
 
PDF
Developing High Performance and Scalable ColdFusion Applications Using Terrac...
Shailendra Prasad
 
PDF
White Paper: EMC FAST Cache — A Detailed Review
EMC
 
PDF
Spring One 2 GX 2014 - CACHING WITH SPRING: ADVANCED TOPICS AND BEST PRACTICES
Michael Plöd
 
Caching for J2ee Enterprise Applications
Debajani Mohanty
 
Best_Practices_for_Managing_Your_Artifactory_Filestore-2.pdf
YoramSamoray2
 
Hibernate jj
Joe Jacob
 
Academy PRO: HTML5 Data storage
Binary Studio
 
Html5 cache mechanism & local storage
Sendhil Kumar Kannan
 
11g r2 flashcache_Tips
Louis liu
 
nHibernate Caching
Guo Albert
 
Caching By Nyros Developer
Nyros Technologies
 
Advanced Hibernate Notes
Kaniska Mandal
 
Hibernate tutorial for beginners
Rahul Jain
 
your browser, my storage
Francesco Fullone
 
Containers and Databases
Fernando Ike
 
Caching in Kentico 11
Christopher Bass
 
Scaling PHP apps
Matteo Moretti
 
Caching technology comparison
Rohit Kelapure
 
Developing High Performance and Scalable ColdFusion Application Using Terraco...
ColdFusionConference
 
Developing High Performance and Scalable ColdFusion Applications Using Terrac...
Shailendra Prasad
 
White Paper: EMC FAST Cache — A Detailed Review
EMC
 
Spring One 2 GX 2014 - CACHING WITH SPRING: ADVANCED TOPICS AND BEST PRACTICES
Michael Plöd
 
Ad

More from Ranjan Kumar (20)

PPT
Introduction to java ee
Ranjan Kumar
 
PPT
Fantastic life views ons
Ranjan Kumar
 
PPS
Lessons on Life
Ranjan Kumar
 
PPS
Story does not End here
Ranjan Kumar
 
PPS
Whata Split Second Looks Like
Ranjan Kumar
 
PPS
Friendship so Sweet
Ranjan Kumar
 
PPS
Dedicate Time
Ranjan Kumar
 
PPS
Paradise on Earth
Ranjan Kumar
 
PPS
Bolivian Highway
Ranjan Kumar
 
PPS
Chinese Proverb
Ranjan Kumar
 
PPS
Warren Buffet
Ranjan Kumar
 
PPS
Dear Son Dear Daughter
Ranjan Kumar
 
PPS
Jara Sochiye
Ranjan Kumar
 
PPS
Blue Beauty
Ranjan Kumar
 
PPS
Alaska Railway Routes
Ranjan Kumar
 
PPS
Poison that Kills the Dreams
Ranjan Kumar
 
PPS
Horrible Jobs
Ranjan Kumar
 
PPS
Best Aviation Photography
Ranjan Kumar
 
PPSX
Role of Attitude
Ranjan Kumar
 
PPS
45 Lesons in Life
Ranjan Kumar
 
Introduction to java ee
Ranjan Kumar
 
Fantastic life views ons
Ranjan Kumar
 
Lessons on Life
Ranjan Kumar
 
Story does not End here
Ranjan Kumar
 
Whata Split Second Looks Like
Ranjan Kumar
 
Friendship so Sweet
Ranjan Kumar
 
Dedicate Time
Ranjan Kumar
 
Paradise on Earth
Ranjan Kumar
 
Bolivian Highway
Ranjan Kumar
 
Chinese Proverb
Ranjan Kumar
 
Warren Buffet
Ranjan Kumar
 
Dear Son Dear Daughter
Ranjan Kumar
 
Jara Sochiye
Ranjan Kumar
 
Blue Beauty
Ranjan Kumar
 
Alaska Railway Routes
Ranjan Kumar
 
Poison that Kills the Dreams
Ranjan Kumar
 
Horrible Jobs
Ranjan Kumar
 
Best Aviation Photography
Ranjan Kumar
 
Role of Attitude
Ranjan Kumar
 
45 Lesons in Life
Ranjan Kumar
 
Ad

Recently uploaded (20)

PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 

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