First knowledge of Hibernate cache, first knowledge of hibernate Cache

Source: Internet
Author: User

First knowledge of Hibernate cache, first knowledge of hibernate Cache

Life is like a cup of coffee, let you And I taste it slowly, taste its bitterness and sweetness ......

1. What is Hibernate cache.

Resolution: in the vernacular, It is the container for caching data.

Official Standard point cache: a concept in the computer field, which is between an application and a permanent data storage source.

Purpose: reduce the frequency of applications directly reading and writing databases, and thus improve the running performance of programs. The cached data is a copy of the data in the data storage source. The cached physical media is usually memory.

Ii. cache is generally divided into three categories

Level 1 Cache

Level 2 Cache

View cache

Iii. Primary Cache

Scenario 1: use the same session for two consecutive queries on the same object

/Query student information public static void select () {// The Session session = HibernateUtil is queried by the class. currentSession (); Grade grade = (Grade) session. get (Grade. class, 14); // output the class information System. out. println (grade. getGname (); Grade grade2 = (Grade) session. get (Grade. class, 14); // output the class information System. out. println (grade2.getGname ());}

Execution result:

Scenario 1: After the first query is completed, close the session object, restart a session, and continue to query the same object.

// Query the student information public static void select () {// The Session session = HibernateUtil is queried by the class. currentSession (); Grade grade = (Grade) session. get (Grade. class, 14); // output the class information System. out. println (grade. getGname (); // disable session HibernateUtil. closeSession (); // obtain the session = HibernateUtil again. currentSession (); Grade grade2 = (Grade) session. get (Grade. class, 14); // output the class information System. out. println (grade2.getGname ());}

Execution result:

 

Resolution:

  1: When I use the same session to access the same object twice without closing the session, only one SQL statement is sent to the database.
* Cause: When I access the database for the first time, Hibernate will automatically query the result.Retain the queried objects to the level-1 cache.
And the object is based onIDIt can also be understood as the primary key value in the database, and then when I access an object again, Hibernate
The mechanism will automatically go to the first-level cache to check whether there are any objects with the same OID as the one I want to query. If there is one, retrieve data directly from the first-level cache.
If the same OID does not exist, it indicates that there is no record I want in the cache, and the database is accessed directly. In this way, an SQL statement is sent again.
2: When I close the session immediately after querying the data for the first time, I re-enable a session to access the same object. Then we will find that it actually sent two SQL statements to the database. Why?
* Cause: in fact, the reason is very simple. Although we say it is the same object accessed, we immediately closed this session and re-opened a session,

At this time, the session we access is inconsistent, that is, the request sent by two different sessions. In this way, we can understand it easily.

As a result, the first-level cache is a session-level cache. When a session ends, the cache in the session will be completely destroyed, and we can only resend one SQL statement.

3. Add the following methods to support level-1 Caching:

 

 

Iv. Secondary Cache

(1) Configure secondary Cache

1. Introduce the following jar package.

Ehcache-1.2.3.jar core library

Backport-util-concurrent.jar

Commons-logging.jar

2. Configure Hibernate. cfg. xml to enable Level 2 Cache

<Property name = "hibernate. cache. use_second_level_cache"> true </property>

 

 

 

3. Configure the second-level cache vendor

<Property name = "hibernate. cache. provider_class"> org. hibernate. cache. EhCacheProvider </property>

 

 

 

4. Specify the second-level cache class

Solution 1: Configure in *. hbm. xml

Add a chche subnode to the child element of the <class element, but this configuration only caches the simple attributes of the object. If you want to cache the elements in the set attribute, the <cache> sub-element must be added to the set element.

<Class name = "Student" table = "STUDENT">

<Cache usage = "read-write"/>

 

 

 

Solution 2: Configure in the large configuration file (hibernate. cfg. xml)

        <Class-cache usage = "read-write" class = "cn. happy. entity. Student"/>

          <Collection-cache usage = "read-write" collection = ""/> -- Annotations can be noted if the configuration is unsuccessful.

 

 

 

Pay attention to the large configuration writing position

Multiple annotations found at this line:

-The content of element type "session-factory" must match "(property *, mapping *, (class-cache | collection-

Cache) *, event *, listener *)".

-Start tag of element <session-factory>

 

* 5. Add the ehcache. xml file under src and obtain the file from etc.

      

<ehcache>    <!-- Sets the path to the directory where cache .data files are created.         If the path is a Java System Property it is replaced by         its value in the running VM.         The following properties are translated:         user.home - User's home directory         user.dir - User's current working directory         java.io.tmpdir - Default temp file path -->    <diskStore path="d:/tmp"/>    <!--Default Cache configuration. These will applied to caches programmatically created through        the CacheManager.        The following attributes are required for defaultCache:        maxInMemory       - Sets the maximum number of objects that will be created in memory        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element                            is never expired.        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used                            if the element is not eternal. Idle time is now - last accessed time        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used                            if the element is not eternal. TTL is now - creation time        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache                            has reached the maxInMemory limit.        -->    <defaultCache        maxElementsInMemory="10000"        eternal="false"        timeToIdleSeconds="120"        timeToLiveSeconds="120"        overflowToDisk="true"        />    <!--Predefined caches.  Add your cache configuration settings here.        If you do not have a configuration for your cache a WARNING will be issued when the        CacheManager starts        The following attributes are required for defaultCache:        name              - Sets the name of the cache. This is used to identify the cache. It must be unique.        maxInMemory       - Sets the maximum number of objects that will be created in memory        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element                            is never expired.        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used                            if the element is not eternal. Idle time is now - last accessed time        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used                            if the element is not eternal. TTL is now - creation time        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache                            has reached the maxInMemory limit.        -->    <!-- Sample cache named sampleCache1        This cache contains a maximum in memory of 10000 elements, and will expire        an element if it is idle for more than 5 minutes and lives for more than        10 minutes.        If there are more than 10000 elements it will overflow to the        disk cache, which in this configuration will go to wherever java.io.tmp is        defined on your system. On a standard Linux system this will be /tmp"        -->    <cache name="sampleCache1"        maxElementsInMemory="10000"        eternal="false"        timeToIdleSeconds="300"        timeToLiveSeconds="600"        overflowToDisk="true"        />    <!-- Sample cache named sampleCache2        This cache contains 1000 elements. Elements will always be held in memory.        They are not expired. -->    <cache name="sampleCache2"        maxElementsInMemory="1000"        eternal="true"        timeToIdleSeconds="0"        timeToLiveSeconds="0"        overflowToDisk="false"        /> -->    <!-- Place configuration for your caches following --></ehcache>

 

(2))Schematic diagram of the second-level cache bulk data

Resolution: every time an object is retrieved from the second-level cache, it is a new object.

(3) What kind of data is suitable for the second-level cache?

1. Rarely modified data

2. Not very important data, allowing occasional Concurrent Data

3. data that will not be accessed concurrently

4. Reference data refers to the constant data for reference supply. It has a limited number of real columns, and its real columns are referenced by the real columns of many other classes. The real columns are rarely or never modified.

 

 

The story is almost over !!!

 

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.