(v) Hibernate cache level

Source: Internet
Author: User

First, Introduction

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.

There is also a cache in Hibernate, which is 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.

second, the cache range

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.

third, 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 transaction        Transaction ts=session.begintransaction ();        With breakpoints, when we finish this step, we print the SELECT statement, and none of the subsequent prints, stating that the        User user1=session.get (User.class, 5) was not fetched from the database;           This get method is first looked up from the session cache, and since it already exists, the direct return reference         User user2=session.get (User.class, 5);        User User3=session.get (User.class, 5);        System.out.println (user1==user2);//true        System.out.println (user1==user3);//true        session.close ();

iv. 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. But instead of updating, we commit 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.

(1)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 the object        Transaction ts=session.begintransaction () with the ID 5,name as Tom,password 123456 from the database;        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 object that is exactly the same as the database, and we 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.

(2) 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 the application explicitly calls the session's flush () method,  -session cleans up the cache exception, and if the object uses the native generation policy generation OID, then the session's Save () method is called to save the object. An INSERT statement to the database is executed immediately.

  

(3) 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 time point 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   

  

 

v. Other APIs for session interface

The--session Save () and persist () methods two methods are used to save the object, which can turn the temporary state into a persistent state. The difference between the two methods is that the OID of a persisted object is returned when the Save method persists the object.     Therefore, when the program executes save, the INSERT statement is executed immediately to return the OID generated by the database. When the persist method persists an object, it is not guaranteed to immediately assign a value to the OID of the persisted object, and the INSERT statement is not immediately generated, but it is possible to assign a value to the OID when the session cleans up the cache. The--session Clear () method empties the Update method of the first-level cache--session the update () method to turn the free object into a persisted object.                    Used to perform the modify operation. The update () method does the following-adding a free object to the current cache, becoming a persisted object-and then planning to execute the UPDATE statement as soon as the Updat                    e transforms the free object into a persisted object, even if no property is modified, and the UPDATE statement is executed when the cache is cleaned up. If you want the session to execute the UPDATE statement only if the property is modified, you can set select-before-update= "true" in the <class> element in the mapping file, and the default is false so that when the Sessi                    On clean cache, a query statement is sent first, and then the UPDATE statement is executed in the same way that the objects and records in the cache are consistent and inconsistent.                    When the update () method turns a free object into a persisted object, an exception is thrown if the same OID persisted object already exists in the session cache.                        For example: Transaction ts=session.begintransaction ();                        User User1=session.get (User.class, 5);         Session.evict (user1);               User User2=session.get (User.class, 5);                        Session.update (user1);                        Ts.commit ();                        Because the session cache is a map structure, the OID is key, and the object is value. When executing the session's Update method, an exception is thrown because a persisted object with the OID of 5 already exists in the cache. -session's Saveorupdate () method Session's Saveorupdate () method also contains the function of the Save () and update () methods if the passed in parameter is a temporary object (OID is null),            The Save method is called. If the parameter passed in is a free object (the OID is not NULL), the Update method is executed.

  

 

  

  

(v) Hibernate cache level

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.