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 hibernateintroductionthirumuru2012
 
01 persistence and domain modeling
01 persistence and domain modeling01 persistence and domain modeling
01 persistence and domain modelingthirumuru2012
 
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.2Vikrant Singh
 
10 Cache Implementation
10  Cache Implementation10  Cache Implementation
10 Cache ImplementationRanjan Kumar
 
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 PresentationRemote DBA Services
 
09 transactions new1
09 transactions new109 transactions new1
09 transactions new1thirumuru2012
 
"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...eLiberatica
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking TourJoshua Long
 
Jug Lugano - Scale over the limits
Jug Lugano - Scale over the limitsJug Lugano - Scale over the limits
Jug Lugano - Scale over the limitsDavide Carnevali
 
Less01 architecture
Less01 architectureLess01 architecture
Less01 architectureAmit Bhalla
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Trainingsourabh aggarwal
 
Owner - Java properties reinvented.
Owner - Java properties reinvented.Owner - Java properties reinvented.
Owner - Java properties reinvented.Luigi Viggiano
 
"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...eLiberatica
 

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

Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 

Recently uploaded (20)

Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 

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