Hibernate cache mechanism (level two cache)

Source: Internet
Author: User

First, why (Why use hibernate cache?) )

Hibernate is a persistent layer framework that accesses physical databases frequently.

Improve application performance by reducing the frequency of application access to physical data sources.

The data in the cache is a copy of the data in the physical data source, the application reads and writes data from the cache at run time, and at a particular moment or event synchronizes the cache and the data from the physical data source.

Ii. What is the principle of hibernate caching? The hibernate cache consists of two main classes: Hibernate cache and Hibernate level two cache.

The 1.Hibernate cache is also known as the "session cache".

The session can not be uninstalled, the session cache is a transaction-scoped cache (the session object's life cycle usually corresponds to a database transaction or an application transaction).

In the first-level cache, each instance of the persisted class has a unique OID.


The 2.Hibernate level two cache is also known as the "Sessionfactory cache".

Because the life cycle of the Sessionfactory object corresponds to the entire process of the application, hibernate level Two caches are process-wide or cluster-wide caches, and concurrency problems may occur, so appropriate concurrent access policies are required. This policy provides a transaction isolation level for cached data.

The second-level cache is optional and is a configurable plug-in, which is not enabled by default under Sessionfactory.

Hibernate provides the Org.hibernate.cache.CacheProvider interface, which acts as an adapter between the cache plug-in and hibernate.

What data is suitable for storage in the second level cache?
1) rarely modified data
2) data that is not very important, allowing occasional concurrent data to occur
3) data that will not be accessed concurrently
4) Constant data
Not suitable for storing data in a second level cache?
1) Frequently modified data
2) never allow concurrent access to data, such as financial data, is never allowed to appear concurrency
3) data that is shared with other apps.

3.Session deferred load implementation to resolve two issues: gracefully close the connection and ensure that the same session is accessed in the request.

Hibernate session is a high-level package of Java.sql.Connection, a session corresponding to a connection.

The session is closed correctly after the HTTP request is completed (the filter implements the normal shutdown of the session); The deferred load must be guaranteed to be the same session (session bound at threadlocal).

4.Hibernate How do I find objects to apply a cache?
When hibernate accesses data objects based on their IDs, the first cache is checked from the session level.

Not found, if a level two cache is configured, then from the level two cache;

If it is not found, then query the database, the results by ID into the cache to delete, update, add data, while updating the cache.

5. The first level cache and the two level cache comparison chart.

First-level caching

Second-level cache

The form of storing data

Interrelated persisted objects

object's bulk data

Scope of the cache

Transaction scope, each transaction has a separate first-level cache

Process scope or cluster scope, the cache is shared across all transactions within the same process or cluster

Concurrent access Policies

Because each transaction has a separate first-level cache, there is no concurrency problem, so there is no need to provide a concurrent access policy

Because multiple transactions access the same data in the level two cache at the same time, an appropriate concurrency access policy must be provided to guarantee a specific transaction isolation level

Data Expiration policy

Objects in the first-level cache never expire unless the application displays empty or empty specific objects

You must provide a data expiration policy, such as the maximum number of objects in the memory-based cache, the longest time the object is allowed to be in the cache, and the maximum idle time that the object is allowed to be in the cache

Physical media

Memory

Memory and hard disk, the object's bulk data is first stored in the memory-based cache, and when the number of objects in memory reaches the maxelementsinmemory value of the data expiration policy, the rest of the objects are written to the hard disk-based cache

Cache software Implementation

Included in the implementation of Hibernate's session

Provided by a third party, hibernate only provides a cache adapter for integrating specific cache plugins into hibernate

How caching is enabled

As long as the session interface to perform the save, update, delete, load, query, hibernate will enable the first-level cache, for bulk operations, such as do not want to enable primary cache, directly through the JDBCAPI to execute

A user can configure a second-level cache on the granularity of a single collection of a single class or class, and if an instance of the class is read frequently, but is rarely modified, consider using a level two cache, only a class or collection is configured with a level two cache, and Hibernate adds its instance to the two cache at runtime.

How the user manages the cache

The first-level cache of physical media is memory, due to the limited capacity of memory, the number of loaded objects must be restricted through appropriate retrieval policies and retrieval methods, the session's Evit () method can display the empty cache of specific objects, but not recommended

Secondary caches of physical media can make memory and hard disk, so the second level cache can hold large volumes of data, the Maxelementsinmemory property of the data expiration policy can control the number of objects in memory, the management of level two cache mainly includes two aspects: Select the persistence class that needs to use the second level cache, Set the appropriate concurrency access policy, select the cache adapter, and set the appropriate data expiration policy. The Sessionfactory Evit () method can also display the empty cache for specific objects, but is not recommended

Third, how (Hibernate caching mechanism is applied?) )

1. Management of first-level caches:

Evit (Object obj) clears the specified persisted object from the first-level cache, freeing the memory resource used by the object to become a free object, from the persisted state to the de-state.

Clear () Clears all persisted objects in the first-level cache and frees up memory resources that it occupies.

Contains (object obj) determines whether the specified object exists in the first-level cache.

Flush () Refreshes the contents of the first-level buffer to keep it in sync with the database data.

2. First-level cache application: Save (). When the session object invokes the Save () method to save an object, the object is placed in the session's cache. Get () and load (). When the session object calls the Get () or load () method to fetch an object from the database, the object is also placed in the session's cache. Use HQL and QBC to query data from the database.

public class client{public static void Main (string[] args) {Session session = Hibernateutil.getsessionfacto        Ry (). Opensession ();        Transaction tx = NULL;            try {/* Open a transaction */tx = Session.begintransaction (); /* Get the Customer object for id= "402881e534fa5a440134fa5a45340002" from the database */Customer Customer1 = (customer) Session.get (Customer            . class, "402881e534fa5a440134fa5a45340002");            System.out.println ("Customer.getusername is" +customer1.getusername ());                        /* Transaction Submission */Tx.commit ();                        System.out.println ("-------------------------------------");            /* Open a new transaction */tx = Session.begintransaction (); /* Get the Customer object for id= "402881e534fa5a440134fa5a45340002" from the database */Customer CUSTOMER2 = (customer) Session.get (Customer            . class, "402881e534fa5a440134fa5a45340002");            System.out.println ("Customer2.getusername is" +customer2.getusername ()); /* ThingsService Submission */Tx.commit ();                        System.out.println ("-------------------------------------");        /* Compare the two get () methods to get whether the object is the same object */System.out.println ("customer1 = = Customer2 result is" + (Customer1==customer2));            } catch (Exception e) {if (tx!=null) {tx.rollback ();        }} finally {Session.close (); }    }}
Results hibernate:     Select        customer0_.id as id0_0_,        customer0_.username as username0_0_,        customer0_. Balance as balance0_0_     from        customer customer0_     where        customer0_.id=?customer.getusername Islisi-------------------------------------Customer2.getusername Islisi-------------------------------------Customer1 = = Customer2 result is true

Only one select SQL statement is included in the output, and customer1 = = Customer2 result is true to indicate that both objects are the same object. The principle is: First call the Get () method, hibernate first retrieves the cache for the lookup object, found that no, Hibernate sends a SELECT statement to the database to fetch the corresponding object, and then put the object in the cache for the next use, the second call to the Get () method , hibernate retrieves the lookup object in the cache first, discovers that it happens to have the lookup object, takes it out of the cache, and no longer retrieves it from the database.

3. Management of Level two cache:

Evict (class arg0, Serializable arg1) clears the persisted object for the specified ID of a class from the level two cache, releasing the resources that the object occupies.

Sessionfactory.evict (Customer.class, New Integer (1));  

Evict (class arg0) clears all persisted objects of the specified class from the level two cache and frees the memory resources it consumes.

Sessionfactory.evict (Customer.class);  

Evictcollection (String arg0) clears the specified collection of all persisted objects of the specified class from the level two cache and frees the memory resources it consumes.

Sessionfactory.evictcollection ("Customer.Orders");  

4. Configuration of Level two cache

Common level Two cache plug-in

EHCache Org.hibernate.cache.EhCacheProvider

Oscache Org.hibernate.cache.OSCacheProvider

Swarmcahe Org.hibernate.cache.SwarmCacheProvider

JBossCache Org.hibernate.cache.TreeCacheProvider

<!--ehcache configuration, Hibernate.cfg.xml--
<!--ehcache.xml--><?xml version= "1.0" encoding= "UTF-8"?>
<ehcache>
<!--
Cache path to Hard disk
-
<diskstore path= "D:/ehcache" ></diskStore>
<!--
Default settings
Maxelementsinmemory: The maximum number of cached objects in the memory.
Eternal: Whether the cached object will never change.
Timetoidleseconds: The time at which the object can be manipulated.
Timetoliveseconds: The lifetime of the object in the cache, and the time-to-post query data is read from the database.
Overflowtodisk: Full memory, whether to cache to the hard disk.
-
<defaultcache maxelementsinmemory= "$" eternal= "false"
timetoidleseconds= "timetoliveseconds=" overflowtodisk= "true" ></defaultCache>
<!--
Specifies the cached object.
The properties that appear below cover the above, not appearing inheritance above.
-
<cache name= "Com.suxiaolei.hibernate.pojos.Order" maxelementsinmemory= "$" eternal= "false"
timetoidleseconds= "timetoliveseconds=" overflowtodisk= "true" ></cache>
</ehcache>
<!--*.hbm.xml--><?xml version= "1.0" encoding= ' UTF-8 '? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">

If there is a one-to-many relationship, you want to cache the associated parties at the time of acquiring a party, you need to add the <cache> sub-tags under the properties of the collection, where the hbm file of the associated object needs to be added under the presence <class> tag <cache > tags, otherwise hibernate will only cache OIDs.

 

Original: http://www.cnblogs.com/wean/archive/2012/05/16/2502724.html

Hibernate cache mechanism (level two cache)

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.