Hibernate cache: First-level cache and level two cache

Source: Internet
Author: User
Tags sessions jboss

1. What is a cache?

Caching is between a physical data source and an application, a container that is temporarily placed in memory for data in a database, and is designed to reduce the number of times an application accesses a physical data source, improving the performance of the application. Hibernate when reading data, according to the cache mechanism in the corresponding cache query, if in the cache to find the required data (we call this "cache hit"), then directly the hit data as a result of the use, to avoid a large number of sending SQL statements to the database query performance loss.

Caching Policy providers:

Provides a hashtable cache, Ehcache,oscache,swarmcache,jboss Cathe2, these caching mechanisms, where Ehcache,oscache is not available for cluster environments (Cluster Safe), and Swarmcache,jboss Cathe2 is possible. The hashtable cache is mostly used for testing, only putting objects in memory, Ehcache,oscache can put objects in memory, or you can put objects on the hard disk (why put them on the hard drive?). explained above).

Hibernate Cache Classification:

One, session cache (also known as transaction cache): Hibernate built-in, can not be removed.

Cache scope: The cache can only be accessed by the current session object. The lifetime of the cache depends on the session's life cycle, and when the session is closed, the cache ends the life cycle.

Second, Sessionfactory cache (also known as application cache): Use a third-party plug-in, pluggable.

Cache scope: The cache is shared by all sessions within the application, and different sessions can be shared. These sessions are likely to be concurrent access caches, so the cache must be updated. The lifecycle of the cache depends on the life cycle of the application, and at the end of the application, the cache ends the lifecycle, and the level two cache exists in the application scope.

First-level caching:

Hibernate some operations related to first-level caching (point in time):

Data into the cache:

1. Save (). When the session object invokes the Save () method to save an object, the object is placed in the session's cache.

2. 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.

3. Use HQL and QBC to query data from the database.

For example: The database has one table as follows:

Use Get () or load () to prove the existence of the cache:

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 (); }    }}

Program Console output:

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

The principle is : in the same session, the first call to get () method, hibernate first retrieve the cache if there is a Lookup object, found no, Hibernate send SELECT statement to the database to remove the corresponding object , and then put the object into the cache for the next use, the second call to the Get () method, hibernate first retrieves the cache for the lookup object, found that there is exactly the lookup object, removed from the cache, no longer go to the database to retrieve, did not send the SELECT statement again.

The data is purged from the cache:

1. Evit () Clears the specified persisted object from the cache, releasing the memory resource occupied by the object, and the specified object becomes a free object from the persisted state to the de-state.
2. Clear () Clears all persisted objects in the cache and frees up memory resources that it occupies.

Other cache operations:

1. Contains () determines whether the specified object exists in the cache.
2. Flush () Refreshes the contents of the buffer and keeps it in sync with the database data.

Second-level cache:
@Testpublic void TestCache2 () {Session session1 = sf.opensession ();//Get Session1session1.begintransaction (); Category C = (category) Session1.load (Category.class, 1); System.out.println (C.getname ()); Session1.gettransaction (). commit (); Session1.close ();

Session Session2 = Sf.opensession ();//Get Session2session2.begintransaction (); Category C2 = (category) Session2.load (Category.class, 1); System.out.println (C2.getname ()); Session2.gettransaction (). commit (); Session2.close ();}

When we restart a session, the second call to load or the Get method to retrieve the same object will re-locate the database, and will send the SELECT statement information.

Cause: One session cannot take the cache in another session.

Performance problems: If it is multi-threaded at the same time to get the category of the object, load an object, this pair of images can be put into memory, but because it is multi-threaded, is distributed in different sessions, so every time to take from the database, which will bring low query performance problems.

Solution: Use level two caching.

1. What is a level two cache?

Sessionfactory-level caches can be present across sessions and can be shared by multiple sessions of the session.

2. Fit into the level two cache:

(1) Frequently visited

(2) Minor changes

(3) Limited quantity

(4) data that is not very important, allowing occasional concurrent data to occur.

Such data is well suited to be placed in a level two cache.

User's rights: The number of users is small, the permissions are not many, not often changed, often be accessed.

such as organizational structures.

Think: What kind of class does the object fit into the level two cache?

Changes frequently, the class inside the object is particularly many, BBs many posts, these posts more than 20,000, which puts in the cache, cannot determine. Unless you are certain that there are some frequently accessed data volumes that are not very large and have very few changes, such data is well suited to be placed in a level two cache.

3. The two-level cache implementation principle:

How does hibernate put the data in a database into a level two cache? Note that you can think of the cache as a map object whose key is used to store the object Oid,value for storing the Pojo. First, when we use Hibernate to query data from the database, retrieve the retrieved data, hibernate puts the OID of the retrieved object into the cache key, and then puts the specific pojo into value, waiting for the next time to query the data again. Hibernate retrieves a first-level cache based on the OID you provide, retrieves a level two cache if it is configured with a level two cache, and sends an SQL statement to the database if it is not, and then puts the queried object into the cache.

4. Using a Level two cache

(1) Open level two cache:

Configure a level two cache for hibernate:

In the main configuration file, Hibernate.cfg.xml:

<!--use level two cache--

<!--use level two cache--
<property name= "Hibernate.cache.use_second_level_cache" >true</property>
<!--set the type of cache, set the provider for the cache--
<property name= "Hibernate.cache.provider_class" >org.hibernate.cache.EhCacheProvider</property>

Or when hibernate is integrated with spring directly into the spring configuration file Applicationcontext.xml

<bean id= "Sessionfactory" class= "Org.springframework.orm.hibernate3.LocalSessionFactoryBean" >     < Property Name= "DataSource" ref= "DataSource"/>     <property name= "mappingresources" >        <list>          <value>com/lp/ecjtu/model/Employee.hbm.xml</value>          <value>com/lp/ecjtu/model/ department.hbm.xml</value>        </list>     </property>     <property name= " Hibernateproperties ">        <value>        hibernate.dialect=org.hibernate.dialect.oracledialect        Hibernate.hbm2ddl.auto=update        hibernate.show_sql=true        hibernate.format_sql=true            Hibernate.cache.use_second_level_cache=true        hibernate.cache.provider_class= Org.hibernate.cache.EhCacheProvider         hibernate.generate_statistics=true                </value>    </ Property></bean>

(2) Configuration Ehcache.xml

<?xml version= "1.0" encoding= "UTF-8"?><ehcache>    <!--        cache to hard drive path--    < 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= "50" 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>

(3) Using a level two cache requires annotations to be added to the entity class:

Ehcache-1.2.3.jar Package Required:

Also need Commons_loging1.1.1.jar package

The utility level two cache can be configured with annotations in the entity class:

@Cache (usage = cacheconcurrencystrategy.read_write)

Load default to use level two cache, that is, when looking for an object, it will go to the level two cache inside to find, if found, do not go to the database to check.

Iterator default will also use the level two cache, some will not go to the database inside, do not send a SELECT statement.

List default to the level two cache to add data, if there is a query, the data will be placed in the level two cache, but the execution of the query will not go to the level two cache, will be in the database check. Cause the query conditions are different in each of the queries.

(4) You can also add a <cache> sub-tag under the <class> tag in the hbm file in the object that needs to be cached:

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

Hibernate cache: First-level cache and 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.