Hibernate Learning (caching)

Source: Internet
Author: User

caching, between applications and persistent data storage sources, is intended to reduce the frequency of application access to physical data sources, thereby improving the performance of the application.

For example, our CPU execution efficiency processing data up to thousands of megabytes per second, and our hard disk read speed is not so high, read hundreds of trillion, this time we use the cache to store data, storage full after the CPU processing.

Hibernate caches are also designed to improve efficiency. Hibernate's cache includes the session cache and the Sessionfactory cache.

The session cache is built-in and cannot be unloaded, and is also known as a hibertnate cache.

The Sessionfactory has a built-in cache and an external cache. Sessionfactory's external cache is a configurable cache plug-in. By default, hibernate does not enable this cache plug-in. A level two cache called Hibernate.

Scope of the cache

The scope of the cache determines the life cycle of the cache and who can access it.

Transaction scope: The cache can only be accessed by the current transaction. The first-level cache is the cache of sessions, and the session object life cycle usually corresponds to a transaction, so it is a transaction-scoped cache.

Process scope: The cache is shared by all the transactions within the process. A secondary cache is a configurable cache plug-in that is managed by sessionfactory, corresponds to the process of the sessionfactory lifecycle and the application, and therefore is a process-wide cache.

Cluster scope: In a clustered environment, the cache is shared by multiple processes on the same machine or on multiple machines.

Hibernate level cache: Session Cache

The session cache is the first-level cache of Hibernate. The session object has a cache. The session cache is a memory space that holds persistent objects.
When the session persists an object through the Save method, the object is added to the session cache.
When the session obtains a persisted object through the Get method, the session first determines whether the object exists in the session cache and, if it exists, does not need to be looked up from the database.

Let's test the existence of the cache:

       //Open TransactionTransaction ts=session.begintransaction (); //Add a breakpoint, and when we do this, we print the SELECT statement, and none of the subsequent prints, and the description does not get from the databaseUser User1=session.get (user.class, 5); //This get method is first looked up from the session cache, and because it already exists, it returns the reference directlyUser User2=session.get (user.class, 5); User User3=session.get (User.class, 5); System.out.println (User1==USER2);//trueSystem.out.println (USER1==USER3);//trueSession.close ();
Mechanism for dirty check and cache cleanup

Let's start by looking at the following example

Transaction ts=session.begintransaction ();        User User1=session.get (user.  Class, 5);        User1.setname ("Swaggy");        Ts.commit ();

We found that we changed the Name property, when the Name property of the object in the session cache was inconsistent with the Name field in the database table. However, we did not perform the update operation, but submitted the transaction directly.
Fortunately, a dirty check is performed automatically when the cache is cleaned up during the session. If the persisted object in the session cache is found to be inconsistent with the records in the database, the database is updated based on the latest properties of the object.
So in this case, the session automatically submits an UPDATE statement that updates the database.

How does the session conduct a dirty check?

When an object is added to the sesion cache, the session copies a snapshot of the object. When the session cleans up the cache, it compares the properties and snapshots of the current object to determine if a change has occurred and, if so, performs the related update operation based on the latest properties.

Let's take a look at the following example to deepen our understanding of snapshots

        // We take out the database with an object        with ID 5,name of Tom,password 123456 Transaction ts=session.begintransaction ();        User User1=session.get (user.  Class, 5);        Session.update (user1);        Session.close ();         
Procedure: Gets the persisted object, puts in the cache, and creates the snapshot, we perform the update, the object in the session cache is compared with the snapshot, there is no change, so the UPDATE statement is not executed.
        // we set up an identical object to the database and print the UPDATE statement        Transaction ts=session.begintransaction ();        User User=new  User ();        User.setid (5);        User.setname ("Tom");        User.setpassword ("123456");        Session.update (user);        Ts.commit ();        Session.close ();

Procedure: Because when we execute the UPDATE statement, the object is placed directly into the cache, but there is no snapshot of the persisted object, so the comparison result is inconsistent, so even though nothing has changed, the UPDATE statement is executed and printed in the console.

When will the cache be cleaned?

    • -By default, the cache is cleaned up first when the commit () method is called. The transaction is then committed to the database.
    • -When a query operation is performed, if the persisted object property in the cache has changed, the cache is cleaned up, the data is synchronized, and the query is guaranteed to be the correct result.
    • -When an application explicitly invokes the flush () method of the session
    • -session the exception to the cleanup cache, if the object is using the native generation policy generation OID, then the INSERT statement to the database is immediately executed when the session's Save () method is called to save the object.

If you do not want the session to clean up the cache at the above default point in time, you can use the Setflushmode () method of the session to set the point in time to clean up the cache.
The Flushmode class defines three cleanup modes.

                            Various query Methods          commit () method        Flush () method-flushmode.auto (default mode) cleanup cleanup                -flushmode.commit              do not clean                up cleanup Clean-flushmode.never do not clean up clean              up   
Hibernate level Two cache: Introduction to Sessionfactory Level two cache

A secondary cache is a pluggable cache plug-in that is managed by Sessionfactory and is a process-wide cache.
Secondary caches may have concurrency problems, so appropriate concurrent access policies are required.
This policy provides a transaction isolation level for the data in the cache.
Hibernate also provides a query cache, which relies on level two caching.

What is stored in the second level cache?

Data that meets the following criteria is suitable for storage in level two caches

    • -data that is rarely modified
    • -Not very important data, allowing for occasional concurrency problems
    • -Reference data (constant data referenced by the means application)

The following data is not suitable for storage in level two cache

    • -data that is often modified
    • -Financial data, absolutely not allowed to appear and issued date
    • -data that is shared with other apps

The cache in the secondary cache is not an object, but an object's bulk data.

Common level Two cache plug-in

The secondary cache is a configurable plugin and Hibernate allows the following cache plugins to be selected

    • -ehcache: Can be used as a process-wide cache. The physical media that holds the data can be a hard disk or memory that supports Hibernate's query cache.
    • -oscache: As a process-wide cache, the physical media that holds the data can be a hard disk or memory, support Hibernate's query cache, and provide a rich cache data expiration policy.
    • -swarmcache: Can be used as a cluster-wide cache and does not support Hibernate's query cache.
    • -jbosscache: Can be used as a cluster-wide cache to support transactional concurrency access policies. Support for Hibernate query caching.

Transaction isolation level for secondary caches

    Transactional (transactional type):        available only in managed environments        provides repeatable read transaction isolation level        applicable to frequently read, rarely modified data        prevents dirty reads and non-repeatable read concurrency problems        Cache support transactions, when an exception occurs, the cache can also roll back    read-write (read-write type);        provides read Committed transaction isolation level applicable to        data        that is often read and seldom modified in a non-clustered environment Prevents dirty reads from        updating the cache when the data in the cache is locked    nonstrict-read-write (non-strictly read-write):        applicable to Very few modified, occasionally allow dirty read data (two transactions at the same time to modify the data is rarely seen)        There is no guarantee that the consistency of the data in the cache and the database        sets a very short expiration time for the cached data so as to avoid dirty reads        do not lock the data in the cache    read-only (read-only):        for data that has never been modified (such as reference data) In        this mode, if the data is updated, there will be a        low level of exception transaction isolation, high concurrency performance        in a clustered environment can also work perfectly

To integrate these third-party cache plugins into Hibernate, Hibernate provides the Org.hibernate.cache.CacheProvider interface
It is the adapter between the cache plug-in and hibernate. Hibernate provides a built-in adapter implementation class for the above four cache plug-ins.
If you need to use a different cache plug-in, simply provide the class that implements the interface for the plug-in.

Using Level Two caching

Configuring Level Two Caching
1. Open Level Two cache
2. Select the persistence class for the level two cache you want to use, and set the concurrency access policy for level two caching.
3. Select the appropriate cache plug-in and configure the configuration file for the cache plug-in.

We demonstrate using the Ehcache plugin

(1) Pilot pack
(2) Configuring the use of Level two cache in Hibernate.cfg.xml

<name= "Hibernate.cache.use_second_level_cache">true</  Property>

(3) Configuring the implementation class using Ehcache

<name= "Hibernate.cache.region.factory_class"> Org.hibernate.cache.EhCacheRegionFactory</Property>

Hibernate allows you to set level two caching on the configuration classes and collections. You can also set the query cache.

(i) Set level two cache on class

Configuration behind the <mapping> elements of the Hibernate.cfg.xml

<!-- usage Sets the isolation level, class sets which classes  -        <  usage= "Read-only"  class= "Com.cad.domain.Customer"/>

Test if the object is stored in level two cache

  Public classDemo {PrivateSession session; @Test Public voidTest () {//reading configuration FilesConfiguration conf=NewConfiguration (). Configure (); //Create factory based on configurationSessionfactory sessionfactory=conf.buildsessionfactory (); Session=sessionfactory.opensession (); Transaction TS=session.begintransaction (); //Get object, print SELECT statementCustomer C1=session.get (customer.class, 7); //clear first-level cachesession.clear (); //gets the object again without printing the SELECT statement, indicating that the object is in a level two cacheCustomer C2=session.get (customer.class, 7);                Ts.commit ();                Session.close ();            Sessionfactory.close (); }        } 

(ii) Set level two buffers on the set

To set the object in the collection to a level two buffer.

<Class-cacheusage= "Read-only"class= "Com.cad.domain.Customer"/>          <Class-cacheusage= "Read-only"class= "Com.cad.domain.Order"/>           <!--Collection sets the collection in an object -          <Collection-cacheusage= "Read-only"Collection= "Com.cad.domain.Customer.orders"/> 

Test it.

 Public classDemo {PrivateSession session; @Test Public voidTest () {//reading configuration FilesConfiguration conf=NewConfiguration (). Configure (); //Create factory based on configurationSessionfactory sessionfactory=conf.buildsessionfactory (); Session=sessionfactory.opensession (); Transaction TS=session.begintransaction (); //print a SELECT statementCustomer C1=session.get (customer.class, 7);  for(Com.cad.domain.Order o:c1.getorders ()) {System.out.println (O.getname ()); }                      //emptying bufferssession.clear (); //look again, do not print, the object in the collection is placed in the level two cacheCustomer C2=session.get (customer.class, 7);  for(Com.cad.domain.Order o:c2.getorders ()) {System.out.println (O.getname ());                    } ts.commit ();                    Session.close ();                Sessionfactory.close (); }            }

Hibernate Learning (caching)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.