SlideShare a Scribd company logo
1 of 30
Professional Open Source™




           Caching




© JBoss, Inc. 2003, 2004.                    07/17/04   1
Caching Scopes
                                                             Professional Open Source™


  Transaction scope cache—Attached to the current unit of work,
   which may be a database transaction or even a conversation. It’s
   valid and used only as long as the unit of work runs. Every unit of
   work has its own cache. Data in this cache isn’t accessed
   concurrently.

  Process scope cache—Shared between many (possibly
   concurrent) units of work or transactions. This means that data in the
   process scope cache is accessed by concurrently running threads,
   obviously with implications on transaction isolation.

  Cluster scope cache—Shared between multiple processes on the
   same machine or between multiple machines in a cluster. Here,
   network communication is an important point worth consideration.




© JBoss, Inc. 2003, 2004.                                                                2
Professional Open Source™


  Hibernate has a two-level cache architecture:

  The first-level cache is the persistence context cache. This is at the
   unit-of-work level.

  It corresponds to one session in Hibernate for a single request and is
   by default enabled for the Hibernate session.

  The second-level cache is either at the process scope or the cluster
   scope. This is the cache of the state of the persistence entities.

  A cache-concurrency strategy defines the transaction isolation details
   for a particular item of data, and the cache provider represents the
   physical cache implementation.



© JBoss, Inc. 2003, 2004.                                                                 3
Using the Second-Level Cache in Hibernate
                                                                  Professional Open Source™


  The cache policy involves setting the following:


           –       Whether the second-level cache is enabled
           – The Hibernate concurrency strategy
           – Cache expiration policies (such as timeout, least recently used,
             and memory sensitive)
           – The physical format of the cache (memory, indexed files, or
             cluster-replicated)




© JBoss, Inc. 2003, 2004.                                                                     4
Concurrency Strategies
                                                                    Professional Open Source™


           – Transactional: This strategy should be used when there is more
             data to read. It prevents stale data in concurrency strategies. It’s
             equivalent to isolation level: repeatable read.

           – Read-write: This maintains a read-committed isolation level.

           – Non-strict read-write: This doesn’t guarantee that you won’t
             read stale data. It doesn’t guarantee consistency between cache
             and database.

           – Read-only: This is appropriate for data that never changes.




© JBoss, Inc. 2003, 2004.                                                                       5
Cache Providers
                            Professional Open Source™




© JBoss, Inc. 2003, 2004.                               6
Professional Open Source™


  Not every cache provider is compatible with every concurrency
   strategies . The compatibility matrix is given in below Table :




© JBoss, Inc. 2003, 2004.                                                              7
Cache Regions
                                                               Professional Open Source™


  Cache regions are handles by which you can reference classes and
   collections in the cache provider configuration and set the expiration
   policies applicable to that region.

  Regions are buckets of data of two types:

  one type contains disassembled data of entity instances,
  the other contains only identifiers of entities that are linked through a
   collection.

  The name of the region is the class name in the case of a class cache
   or the class name together with the property name in the case of a
   collection cache.




© JBoss, Inc. 2003, 2004.                                                                  8
Caching Query Results
                                                              Professional Open Source™


  A query’s result set can be configured to be cached. By default,
   caching is disabled, and every HQL, JPA QL, and Criteria query hits
   the database.

  You enable the query cache as follows:

  hibernate.cache.use_query_cache = true

  In addition to setting this configuration property, you should use the
   org.hibernate.Query interface:

  Query bookQuery = session.createQuery("from Book");
  bookQuery.setCacheable(true);
  The setCacheable() method enables the result to be cached.


© JBoss, Inc. 2003, 2004.                                                                 9
First Level Cache
                                                           Professional Open Source™




  If you inspect the SQL statements executed by Hibernate, you find
   that only one database query is made.

  That means Hibernate is caching your objects in the same session.
   This kind of caching is called first-level caching, and its caching
   scope is a session.




© JBoss, Inc. 2003, 2004.                                                              10
Professional Open Source™




  Two database queries are made. That means Hibernate isn’t caching
   the persistent objects across different sessions by default.

  You need to turn on this second-level caching, whose caching
   scope is a session factory.



© JBoss, Inc. 2003, 2004.                                                           11
Professional Open Source™




    CONFIGURING SECOND LEVEL
    CACHE




© JBoss, Inc. 2003, 2004.                               12
Configuring cache provider
                                                            Professional Open Source™


  To turn on the second-level cache, the first step is to choose a cache
   provider in hibernate.cfg.xml.




© JBoss, Inc. 2003, 2004.                                                               13
Professional Open Source™


  You can configure EHCache through the configuration file
   ehcache.xml, located in the source root folder.




© JBoss, Inc. 2003, 2004.                                                            14
Professional Open Source™


  To monitor Hibernate’s caching activities at runtime, add the following
   line to the log4j configuration file log4j.properties:




© JBoss, Inc. 2003, 2004.                                                               15
Professional Open Source™


  When you enable a class with the second-level cache, Hibernate
   doesn’t store the actual instances in cache.

  Instead it caches the individual properties of that object.

  For example, the instance of Book isn’t cached—rather, the
   properties in the book object like name and price are cached.

  The cached objects are stored in a region that has the same name as
   the persistent class, such as com.training.Book.




© JBoss, Inc. 2003, 2004.                                                                    16
Configuring cache usage strategy
                                          Professional Open Source™




© JBoss, Inc. 2003, 2004.                                             17
Professional Open Source™




  When the Book class is cached, only one SQL query is made,
   even though the book object is loaded
  more than once in two different sessions. Because the second call to
   the database is avoided, the query’s performance improves:


© JBoss, Inc. 2003, 2004.                                                              18
Professional Open Source™




        If you modify the book object in one session and flush the
        changes, an exception will be thrown for updating a read-only
        object.




© JBoss, Inc. 2003, 2004.                                                                 19
Professional Open Source™


  So, for an updatable object, you should choose another cache usage:
   read-write.

  Hibernate invalidates the object from cache before it’s updated:




© JBoss, Inc. 2003, 2004.                                                              20
Professional Open Source™


  You can invalidate either one instance or all instances of a persistent
   class:

       factory.evict(Book.class);
       factory.evict(Book.class, id);
       factory.evictEntity("com.training.Book");
       factory.evictEntity("com.training.Book", id);




© JBoss, Inc. 2003, 2004.                                                                21
Professional Open Source™


  CacheMode options are provided to control the interaction of
   Hibernate with the second level cache:




© JBoss, Inc. 2003, 2004.                                                         22
CacheModes
                                                         Professional Open Source™


  CacheMode.IGNORE: Hibernate doesn’t interact with the second-
   level cache. When entities cached in the second-level cache are
   updated, Hibernate invalidates them.
  • CacheMode.GET: Hibernate only reads and doesn’t add items
   to the second-level cache. When entities cached in the second-level
   cache are updated, Hibernate invalidates them.

  CacheMode.PUT: Hibernate only adds and doesn’t add read from
   the second-level cache. When entities cached in the second-level
   cache are updated, Hibernate invalidates them.

  • CacheMode.REFRESH: Hibernate only adds and doesn’t read
   from the second-level cache. In this mode, the setting of
   hibernate.cache.use_minimal_puts is bypassed,
  as the refresh is forced.


© JBoss, Inc. 2003, 2004.                                                            23
Professional Open Source™




         CACHING ASSOCIATIONS




© JBoss, Inc. 2003, 2004.                               24
Professional Open Source™




  Is a book’s associated publisher object cached when its parent
   book object is cached?




© JBoss, Inc. 2003, 2004.                                                         25
Professional Open Source™




        If you initialize the association in two different sessions, it’s
        loaded as many times as the initialization is made.

        This is because Hibernate caches only the identifier of
        publisher in Book’s region



© JBoss, Inc. 2003, 2004.                                                                   26
Professional Open Source™


  To cache the publisher objects in their own region, you need to
   enable caching for the Publisher class. You can do it the same way
   as for the Book class.

  The cached publisher objects are stored in a region with the name
   com.training.bookshop.Publisher:

       <hibernate-mapping package="com.training.bookshop">
       <class name="Publisher" table="PUBLISHER">
       <cache usage="read-write" />
       ...
       </class>
       </hibernate-mapping>




© JBoss, Inc. 2003, 2004.                                                             27
Caching Collections
                                                           Professional Open Source™




              factory.evictCollection("com.training.Book.chapters");
              factory.evictCollection("com.training.Book.chapters",
              id);




© JBoss, Inc. 2003, 2004.                                                              28
Caching Queries
                                                           Professional Open Source™


  By default, the HQL queries aren’t cached. You must first enable the
   query cache in the Hibernate configuration file:




© JBoss, Inc. 2003, 2004.                                                              29
Professional Open Source™


  The setting cache.use_query_cache creates two cache regions:
    – one holding the cached query result sets
    – the other holding timestamps of the more recent updates to
      queryable tables.

  By default, the queries aren’t cached. In addition to using the previous
   setting, to enable caching,
  you need to call Query.setCacheable(true).

  This allows the query to look for existing cache results or add
  the results of the query to the cache.

  The query result is cached in a
  region named org.hibernate.cache.QueryCache by default.


© JBoss, Inc. 2003, 2004.                                                                30

More Related Content

Similar to 13 caching latest

02 hibernateintroduction
02 hibernateintroduction02 hibernateintroduction
02 hibernateintroduction
thirumuru2012
 
01 persistence and domain modeling
01 persistence and domain modeling01 persistence and domain modeling
01 persistence and domain modeling
thirumuru2012
 
Oracle essbase 11.1.1 vs 11.1.2
Oracle essbase 11.1.1 vs 11.1.2Oracle essbase 11.1.1 vs 11.1.2
Oracle essbase 11.1.1 vs 11.1.2
Vikrant Singh
 
10 Cache Implementation
10  Cache Implementation10  Cache Implementation
10 Cache Implementation
Ranjan Kumar
 
09 transactions new1
09 transactions new109 transactions new1
09 transactions new1
thirumuru2012
 
Jug Lugano - Scale over the limits
Jug Lugano - Scale over the limitsJug Lugano - Scale over the limits
Jug Lugano - Scale over the limits
Davide Carnevali
 
Less01 architecture
Less01 architectureLess01 architecture
Less01 architecture
Amit Bhalla
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Training
sourabh aggarwal
 

Similar to 13 caching latest (20)

14 hql
14 hql14 hql
14 hql
 
02 hibernateintroduction
02 hibernateintroduction02 hibernateintroduction
02 hibernateintroduction
 
15 jpaql
15 jpaql15 jpaql
15 jpaql
 
01 persistence and domain modeling
01 persistence and domain modeling01 persistence and domain modeling
01 persistence and domain modeling
 
15 jpa
15 jpa15 jpa
15 jpa
 
14 criteria api
14 criteria api14 criteria api
14 criteria api
 
15 jpa introduction
15 jpa introduction15 jpa introduction
15 jpa introduction
 
Oracle essbase 11.1.1 vs 11.1.2
Oracle essbase 11.1.1 vs 11.1.2Oracle essbase 11.1.1 vs 11.1.2
Oracle essbase 11.1.1 vs 11.1.2
 
10 Cache Implementation
10  Cache Implementation10  Cache Implementation
10 Cache Implementation
 
Remote DBA team-1Z0-042 Oracle Sga In Nutshell Oracle Dba Learn By Presentation
Remote DBA team-1Z0-042 Oracle Sga In Nutshell Oracle Dba Learn By PresentationRemote DBA team-1Z0-042 Oracle Sga In Nutshell Oracle Dba Learn By Presentation
Remote DBA team-1Z0-042 Oracle Sga In Nutshell Oracle Dba Learn By Presentation
 
09 transactions new1
09 transactions new109 transactions new1
09 transactions new1
 
"JBoss clustering solutions Mission Critical Enterprise" by Mircea Markus @ e...
"JBoss clustering solutions Mission Critical Enterprise" by Mircea Markus @ e..."JBoss clustering solutions Mission Critical Enterprise" by Mircea Markus @ e...
"JBoss clustering solutions Mission Critical Enterprise" by Mircea Markus @ e...
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking Tour
 
Jug Lugano - Scale over the limits
Jug Lugano - Scale over the limitsJug Lugano - Scale over the limits
Jug Lugano - Scale over the limits
 
Less01 architecture
Less01 architectureLess01 architecture
Less01 architecture
 
09 transactions new
09 transactions new09 transactions new
09 transactions new
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Training
 
Owner - Java properties reinvented.
Owner - Java properties reinvented.Owner - Java properties reinvented.
Owner - Java properties reinvented.
 
"The Open Source effect in the Storage world" by George Mitropoulos @ eLibera...
"The Open Source effect in the Storage world" by George Mitropoulos @ eLibera..."The Open Source effect in the Storage world" by George Mitropoulos @ eLibera...
"The Open Source effect in the Storage world" by George Mitropoulos @ eLibera...
 
hibernate
hibernatehibernate
hibernate
 

Recently uploaded

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
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
Earley Information Science
 
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
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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 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
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
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
 
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
 
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
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.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?
 

13 caching latest

  • 1. Professional Open Source™ Caching © JBoss, Inc. 2003, 2004. 07/17/04 1
  • 2. Caching Scopes Professional Open Source™  Transaction scope cache—Attached to the current unit of work, which may be a database transaction or even a conversation. It’s valid and used only as long as the unit of work runs. Every unit of work has its own cache. Data in this cache isn’t accessed concurrently.  Process scope cache—Shared between many (possibly concurrent) units of work or transactions. This means that data in the process scope cache is accessed by concurrently running threads, obviously with implications on transaction isolation.  Cluster scope cache—Shared between multiple processes on the same machine or between multiple machines in a cluster. Here, network communication is an important point worth consideration. © JBoss, Inc. 2003, 2004. 2
  • 3. Professional Open Source™  Hibernate has a two-level cache architecture:  The first-level cache is the persistence context cache. This is at the unit-of-work level.  It corresponds to one session in Hibernate for a single request and is by default enabled for the Hibernate session.  The second-level cache is either at the process scope or the cluster scope. This is the cache of the state of the persistence entities.  A cache-concurrency strategy defines the transaction isolation details for a particular item of data, and the cache provider represents the physical cache implementation. © JBoss, Inc. 2003, 2004. 3
  • 4. Using the Second-Level Cache in Hibernate Professional Open Source™  The cache policy involves setting the following: – Whether the second-level cache is enabled – The Hibernate concurrency strategy – Cache expiration policies (such as timeout, least recently used, and memory sensitive) – The physical format of the cache (memory, indexed files, or cluster-replicated) © JBoss, Inc. 2003, 2004. 4
  • 5. Concurrency Strategies Professional Open Source™ – Transactional: This strategy should be used when there is more data to read. It prevents stale data in concurrency strategies. It’s equivalent to isolation level: repeatable read. – Read-write: This maintains a read-committed isolation level. – Non-strict read-write: This doesn’t guarantee that you won’t read stale data. It doesn’t guarantee consistency between cache and database. – Read-only: This is appropriate for data that never changes. © JBoss, Inc. 2003, 2004. 5
  • 6. Cache Providers Professional Open Source™ © JBoss, Inc. 2003, 2004. 6
  • 7. Professional Open Source™  Not every cache provider is compatible with every concurrency strategies . The compatibility matrix is given in below Table : © JBoss, Inc. 2003, 2004. 7
  • 8. Cache Regions Professional Open Source™  Cache regions are handles by which you can reference classes and collections in the cache provider configuration and set the expiration policies applicable to that region.  Regions are buckets of data of two types:  one type contains disassembled data of entity instances,  the other contains only identifiers of entities that are linked through a collection.  The name of the region is the class name in the case of a class cache or the class name together with the property name in the case of a collection cache. © JBoss, Inc. 2003, 2004. 8
  • 9. Caching Query Results Professional Open Source™  A query’s result set can be configured to be cached. By default, caching is disabled, and every HQL, JPA QL, and Criteria query hits the database.  You enable the query cache as follows:  hibernate.cache.use_query_cache = true  In addition to setting this configuration property, you should use the org.hibernate.Query interface:  Query bookQuery = session.createQuery("from Book");  bookQuery.setCacheable(true);  The setCacheable() method enables the result to be cached. © JBoss, Inc. 2003, 2004. 9
  • 10. First Level Cache Professional Open Source™  If you inspect the SQL statements executed by Hibernate, you find that only one database query is made.  That means Hibernate is caching your objects in the same session. This kind of caching is called first-level caching, and its caching scope is a session. © JBoss, Inc. 2003, 2004. 10
  • 11. Professional Open Source™  Two database queries are made. That means Hibernate isn’t caching the persistent objects across different sessions by default.  You need to turn on this second-level caching, whose caching scope is a session factory. © JBoss, Inc. 2003, 2004. 11
  • 12. Professional Open Source™ CONFIGURING SECOND LEVEL CACHE © JBoss, Inc. 2003, 2004. 12
  • 13. Configuring cache provider Professional Open Source™  To turn on the second-level cache, the first step is to choose a cache provider in hibernate.cfg.xml. © JBoss, Inc. 2003, 2004. 13
  • 14. Professional Open Source™  You can configure EHCache through the configuration file ehcache.xml, located in the source root folder. © JBoss, Inc. 2003, 2004. 14
  • 15. Professional Open Source™  To monitor Hibernate’s caching activities at runtime, add the following line to the log4j configuration file log4j.properties: © JBoss, Inc. 2003, 2004. 15
  • 16. Professional Open Source™  When you enable a class with the second-level cache, Hibernate doesn’t store the actual instances in cache.  Instead it caches the individual properties of that object.  For example, the instance of Book isn’t cached—rather, the properties in the book object like name and price are cached.  The cached objects are stored in a region that has the same name as the persistent class, such as com.training.Book. © JBoss, Inc. 2003, 2004. 16
  • 17. Configuring cache usage strategy Professional Open Source™ © JBoss, Inc. 2003, 2004. 17
  • 18. Professional Open Source™  When the Book class is cached, only one SQL query is made, even though the book object is loaded  more than once in two different sessions. Because the second call to the database is avoided, the query’s performance improves: © JBoss, Inc. 2003, 2004. 18
  • 19. Professional Open Source™ If you modify the book object in one session and flush the changes, an exception will be thrown for updating a read-only object. © JBoss, Inc. 2003, 2004. 19
  • 20. Professional Open Source™  So, for an updatable object, you should choose another cache usage: read-write.  Hibernate invalidates the object from cache before it’s updated: © JBoss, Inc. 2003, 2004. 20
  • 21. Professional Open Source™  You can invalidate either one instance or all instances of a persistent class:  factory.evict(Book.class);  factory.evict(Book.class, id);  factory.evictEntity("com.training.Book");  factory.evictEntity("com.training.Book", id); © JBoss, Inc. 2003, 2004. 21
  • 22. Professional Open Source™  CacheMode options are provided to control the interaction of Hibernate with the second level cache: © JBoss, Inc. 2003, 2004. 22
  • 23. CacheModes Professional Open Source™  CacheMode.IGNORE: Hibernate doesn’t interact with the second- level cache. When entities cached in the second-level cache are updated, Hibernate invalidates them.  • CacheMode.GET: Hibernate only reads and doesn’t add items to the second-level cache. When entities cached in the second-level cache are updated, Hibernate invalidates them.  CacheMode.PUT: Hibernate only adds and doesn’t add read from the second-level cache. When entities cached in the second-level cache are updated, Hibernate invalidates them.  • CacheMode.REFRESH: Hibernate only adds and doesn’t read from the second-level cache. In this mode, the setting of hibernate.cache.use_minimal_puts is bypassed,  as the refresh is forced. © JBoss, Inc. 2003, 2004. 23
  • 24. Professional Open Source™ CACHING ASSOCIATIONS © JBoss, Inc. 2003, 2004. 24
  • 25. Professional Open Source™  Is a book’s associated publisher object cached when its parent book object is cached? © JBoss, Inc. 2003, 2004. 25
  • 26. Professional Open Source™ If you initialize the association in two different sessions, it’s loaded as many times as the initialization is made. This is because Hibernate caches only the identifier of publisher in Book’s region © JBoss, Inc. 2003, 2004. 26
  • 27. Professional Open Source™  To cache the publisher objects in their own region, you need to enable caching for the Publisher class. You can do it the same way as for the Book class.  The cached publisher objects are stored in a region with the name com.training.bookshop.Publisher:  <hibernate-mapping package="com.training.bookshop">  <class name="Publisher" table="PUBLISHER">  <cache usage="read-write" />  ...  </class>  </hibernate-mapping> © JBoss, Inc. 2003, 2004. 27
  • 28. Caching Collections Professional Open Source™ factory.evictCollection("com.training.Book.chapters"); factory.evictCollection("com.training.Book.chapters", id); © JBoss, Inc. 2003, 2004. 28
  • 29. Caching Queries Professional Open Source™  By default, the HQL queries aren’t cached. You must first enable the query cache in the Hibernate configuration file: © JBoss, Inc. 2003, 2004. 29
  • 30. Professional Open Source™  The setting cache.use_query_cache creates two cache regions: – one holding the cached query result sets – the other holding timestamps of the more recent updates to queryable tables.  By default, the queries aren’t cached. In addition to using the previous setting, to enable caching,  you need to call Query.setCacheable(true).  This allows the query to look for existing cache results or add  the results of the query to the cache.  The query result is cached in a  region named org.hibernate.cache.QueryCache by default. © JBoss, Inc. 2003, 2004. 30