Hibernate Cache Mechanism 2-hibernate second-level cache data cache

Source: Internet
Author: User
For ORM such as Hibernate, caching is particularly important, and it is the key to improving the performance of the persistent layer. in simple terms, Hibernate encapsulates JDBC to manage the internal status and map the or relationship. However, it reduces data access efficiency and performance, caching is an important way to make up for this shortcoming.

Cache is a temporary container of database data in the memory, including temporary copying of database data in the memory. It is located in the middle of the database and database access layer. when querying data, Orm first searches for the relevant data in the cache based on its own Cache Management Policy. If the required data is found, it will be directly used as the result, this avoids the overhead of Database Calling performance. compared with memory operations, Database Calling is a costly process.

Generally, the cache in Orm is divided into the following types:

1. transaction-level cache: data cache within the current transaction scope. in hibernate, the transaction-level cache is implemented based on the session lifecycle. Each session has a data cache, which exists with the creation of the session and perish with the destruction of the session, it is also called session level cache.

2. application-level cache: indicates the shared cache in the access subset of an independent database in an application or application. This cache can be shared by multiple transactions (database transactions or application transactions ), the cache sharing policy between transactions is closely related to the transaction isolation mechanism. in hibernate, the application-level cache is implemented by sessionfactory. All session instances created by one sessionfactory share this cache, which is also called sessionfactory level cache.

3. distributed cache: A cache policy shared by multiple JVMs on multiple application instances. distributed cache is composed of multiple application-level cache instances. It synchronizes data between cache instances through a remote mechanism (RMI, JMS) and modifies data of any instance, the data status of the entire cluster is synchronized.

Hibernate data cache:

1. Internal cache (session level cache is also called a level-1 cache ):

Example:

Java code
Public class test {

Public void get (){

Session session = hibernatesessionfactory. getsession ();
Tuser t = (Tuser) Session. Get ("hibernate. Tuser", 2 );
System. Out. println (T. getname ());
Session. Close ();
}

}

Test: print an SQL statement in the console: hibernate: Select tuser0 _. ID as id0_0 _, tuser0 _. name as name0_0 _, tuser0 _. sex as sex0_0 _ from test. t_user tuser0 _ Where tuser0 _. id =? Indicates that a database call is performed.

The code is changed as follows:

Public class test {

Public void get (){

Session session = hibernatesessionfactory. getsession ();
Tuser t = (Tuser) Session. Get ("hibernate. Tuser", 2 );
System. Out. println (T. getname ());
Tuser TT = (Tuser) Session. Get ("hibernate. Tuser", 2 );
System. Out. println (TT. getname ());
Session. Close ();

}

}

Test again: After two queries, only one SQL statement is displayed on the console: hibernate: Select tuser0 _. ID as id0_0 _, tuser0 _. name as name0_0 _, tuser0 _. sex as sex0_0 _ from test. t_user tuser0 _ Where tuser0 _. id =? It indicates that only one database call is performed.

Then change the Code as follows:

Public class test {

Public void get (){

Session session = hibernatesessionfactory. getsession ();
Tuser t = (Tuser) Session. Get ("hibernate. Tuser", 2 );
System. Out. println (T. getname ());
Session. Close ();
Session session1 = hibernatesessionfactory. getsession ();
Tuser TT = (Tuser) session1.get ("hibernate. Tuser", 2 );
System. Out. println (TT. getname ());
Session1.close ();

}

}

Continue test: Print two SQL statements on the console: hibernate: Select tuser0 _. ID as id0_0 _, tuser0 _. name as name0_0 _, tuser0 _. sex as sex0_0 _ from test. t_user tuser0 _ Where tuser0 _. id =?
Hibernate: Select tuser0 _. ID as id0_0 _, tuser0 _. Name as name0_0 _, tuser0 _. Sex as sex0_0 _ from test. t_user tuser0 _ Where tuser0 _. ID =?

Conclusion: hibernate always queries the database in the cache. For example, if there is no required data in the cache, It queries the database. the internal cache of Hibernate is based on the session lifecycle. That is to say, it exists in each session. It exists with the creation of the session and perish with the destruction of the session, generally, the internal cache is automatically maintained by Hibernate and does not require human intervention. Of course, you can perform the following operations as needed: Session. evict (object) (clears the specified object from the internal cache), session. clear () (clear internal cache ). (For example, adding a session between two queries. clear () will clear the internal cache so that two identical queries within a sesion will perform two operations on the database ).

2. Level-2 Cache: (sometimes called sessionfactory level cache)

Hibernate itself does not provide the product implementation of level 2 cache (only a simple cache based on hashtable is provided for debugging). Here I am using a third-party cache component: ehcache. hibernate's second-level cache implementation requires the following configuration (hibernate3 ):

Add the following in hibernate. cfg. xml:

<Property name = "cache. provider_class"> org. hibernate. cache. ehcacheprovider </property>
<Property name = "hibernate. cache. use_query_cache"> true </property>

Then add the following in the ing file:
<Cache Usage = "read-only"/>

Test the code above: the console outputs an additional [warn] (cachefactory. java: 43)-read-only cache configured for mutable class: hibernate. tuser, level 2 Cache enabled successfully !!

Java code
Public class test {

Public void executequery (){

List list = new arraylist ();
Session session = hibernatesessionfactory. getsession ();
Query query = session. createquery ("from Tuser t ");
Query. setcacheable (true); // activate the query cache.
List = query. List ();
Session. Close ();

}
Public void get (){

Session session = hibernatesessionfactory. getsession ();
Tuser t = (Tuser) Session. Get ("hibernate. Tuser", 2 );
System. Out. println (T. getname ());
Session. Close ();

}

}

Test: the console outputs only one SQL statement: hibernate: Select tuser0 _. ID as id0 _, tuser0 _. name as name0 _, tuser0 _. sex as sex0 _ from test. t_user tuser0 _ (query = session. createquery ("from Tuser t") refers to the SQL statement corresponding to the Code ). the executequery () method and get () method use different sessions !! However, the executequery () method and get () method only perform one operation on the database. This means that the second-level cache is working.

Conclusion: The Hibernate second-level cache is sessionfactory-level, which allows multiple sessions to be shared. Third-party cache components are required for use. The new hibernate version uses ehcache as the default second-level cache.

Cache synchronization policy: the cache synchronization policy determines the access rules of Data Objects in the cache. We must specify the corresponding cache synchronization policy for each object class. hibernate provides four different cache synchronization policies: (remember only one concept for the time being)

1. Read-Only: Read-Only. data that will not change can be used.

2. nonstrict-read-write: if the program does not have strict requirements on Data Synchronization under concurrent access and the data update frequency is low, this cache synchronization policy can achieve better performance.

3. read-write: strict read/write cache. the read committed transaction isolation level is implemented based on the timestamp determination mechanism. it is used when data synchronization is required, but does not support distributed caching. The most frequently used cache synchronization policy is used in actual applications.

4. transactional: Transaction cache, which must run in the JTA transaction environment. in this cache, cache-related operations are added to transactions (this cache is similar to a memory database), such as transaction failure, the data in the buffer pool will be rolled back to the status before the start of the transaction. transaction caching achieves the transaction isolation level of "Repeatable read", effectively ensuring data legitimacy and adapting to the cache of key data. In hibernate's built-in cache, only jbosscache supports transaction 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.