Hibernate Level 1 cache, level 2 cache, and query Cache

Source: Internet
Author: User
Tags configuration settings

Level 1 cache and level 2 Cache

A. level 1 cache (Session-level cache): load the same object twice in a session. During load, Hibernate first searches for the object in the session cache, load data to the database if not found. Therefore, when an object is loaded twice in the same session, only one SQL statement is sent.

B. The second-level cache is the sessionfactory-level cache. hibernate supports multiple second-level caches.

Bytes -------------------------------------------------------------------------------------------------------------------------

Steps for second-level cache:

1. Add the following in hibernate. cfg. xml:

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

Hibernate sessionfactory configuration in applicationcontext. xml:

<Property name = "hibernateproperties">
<Props>
<Prop key = "hibernate. dialect">
Org. hibernate. dialect. oracledialect
</Prop>
<Prop key = "hibernate. show_ SQL"> false </prop>
<Prop key = "hibernate. cache. use_second_level_cache"> true </prop>

<Prop key = "hibernate. cache. provider_class"> org. hibernate. cache. ehcacheprovider </prop>

<Prop key = "hibernate. cache. use_query_cache"> true </prop>

<! --
<Prop key = "hibernate. hbm2ddl. Auto"> Update </prop>
-->
</Props>
</Property>

2. Put the ehcache. xml file in the hibernate package under the src directory.

<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="java.io.tmpdir"/>    <!--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="1200"        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>

 

I. required attributes:

Name: The name of the cache. It must be unique to identify different caches.

Maxelementsinmemory: Maximum number of cache elements in memory management.

Maxelementsondisk: The maximum number of cache elements for disk management. The default value is 0, which means there is no limit.

Eternal: Sets whether the element is persistent. If it is set to true, the cached element will not expire.

Overflowtodisk: Determines whether to transfer data to the disk when the memory is full.

II. The following are optional attributes:

Timetoidleseconds: Sets the time when the element is idle before it expires. It is only valid for non-persistent cache objects. The default value is 0, and the value is 0, which means that the element can be idle for an unlimited period of time.

Timetoliveseconds: Set the time from creation to expiration of an element. Similar to timetoidleseconds.

Diskpersistent: Set whether to store disks when the VM is restarted. The default value is false. (For small security applications, set this value to true ).

Diskexpirythreadintervalseconds: The time when the disk thread is accessed.

Diskspoolbuffersizemb: The buffer size when the disk is saved. The default value is 30 mb. Each cache has its own buffer.

Memorystoreevictionpolicy: Element eviction cache rule. There are three types, which are least recently used by recently used (LRU) and default. First in first out (FIFO), first in first out. Less frequently used (specified as LFU) is used at least.
In addition to the defaultcache cache, the above ehcache. xml file also contains samplecache1 and samplecache2. You can specify the cache when setting cache for objects.
3. @ ecache annotation, for example:

@Entity@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)public class Permission{private int id;private String name;@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}}
 
 

4. Add the ehcache-1.5.0.jar package, under the hibernate-distribution-3.6.0.Final \ Lib \ optional \ ehcache directory Note: ehcache uses the commons-logging package, also add the Level 2 Cache summary:

A. Load and iterator use second-level cache by default.

B. List adds data to the second-level cache by default, but it is not used for query.

Bytes ----------------------------------------------------------------------------------------------------
Query cache:

To use the second-level cache for query, you must enable the query cache:

<Property name = "hibernate. cache. use_query_cache"> true </property>
Note: A. the query cache depends on the second-level cache. The second-level cache must be enabled.
B. the query cache takes effect only when the query conditions are the same. It does not take effect if the conditions are different.

C. Call the setcachable (true) method of query to specify that the second-level cache is used.

Source code eg:

Session session = sf.openSession();session.beginTransaction();List<Category> categories = (List<Category>)session.createQuery("from Category").setCacheable(true).list();session.getTransaction().commit();session.close();Session session2 = sf.openSession();session2.beginTransaction();List<Category> categories2 = (List<Category>)session2.createQuery("from Category").setCacheable(true).list();session2.getTransaction().commit();session2.close();

Cache algorithm:

1. LRU: least recently used by least recently used

2. LFU: least frequently used (hit rate)

3. FIFO: first in first out is similar to an array.

Ehcache supports all three algorithms. we can add the following in ehcache. xml:

<Defaultcache maxelementsinmemory = "10000" <! -- Maximum number of cache storage --> eternal = "false" <! -- Set whether the element is persistent. If it is set to true, the cache element will not expire --> timetoidleseconds = "120" <! -- Set the idle time of the element before expiration, which is only valid for non-persistent cache objects. The default value is 0. If the value is 0, the element can be idle for an unlimited period of time. --> timetoliveseconds = "1200" <! -- Set the time for the element from creation to expiration. Others are similar to timetoidleseconds --> overflowtodisk = "true" <! -- Set whether to transfer data to the disk when the memory is full -->
        memoryStoreEvictionPolicy=“LRU”

        />

Good article: http://blog.csdn.net/nuoyan666/article/details/6577732

Http://www.ibm.com/developerworks/cn/java/j-lo-ehcache/index.html (cluster, have time to watch)

Http://hi.baidu.com/yinaddress/blog/item/f333f0d9af38f93e33fa1c28.html

Http://hi.baidu.com/liang125353769/blog/item/a5ec79eb571b44cbd439c92d.html

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.