1. 程式人生 > >Hibernate框架中的快取技術詳解

Hibernate框架中的快取技術詳解

Hibernate框架的快取分為Session的快取、SessionFactory的快取,也稱為一級快取和二級快取。

一級快取:

一級快取是Session級的快取,其生命週期很短,與Session相互對應,由Hibernate進行管理,屬於事務範圍的快取。當程式呼叫 Session的load()方法、get()方法、save()方法、saveOrUpdate()方法、update()方法或查詢介面方法時,Hibernate會對實體物件進行快取;當通過load()方法或get()方法查詢實體物件時,Hibernate會首先到快取中查詢,在找不到實體對像的情況下,Hibernate才會發出SQL語句到資料庫中查詢,從而提高了Hibernate的使用效率。

舉個例子來說吧:

package com.xqh.util;
import org.hibernate.Session;
import com.xqh.model.User;
public class Test {
public static void main(String[] args) {
Session session = null;
try {
session = HibernateUtil.getSession(); // 獲取session
session.beginTransaction(); //開啟事務
System.out.println("第一次查詢:");
User user = (User)session.get(User.class, new Integer(1));
System.out.println("使用者名稱:" + user.getName());
System.out.println("第二次查詢:");
User user1 = (User)session.get(User.class, 1);
System.out.println("使用者名稱:" + user1.getName());
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
// 出錯將回滾事務
session.getTransaction().rollback();
} finally {
// 關閉Session物件
HibernateUtil.closeSession(session);
}
}
}
當程式通過get()方法第一次查使用者物件時,Hibernate會發出一條SQL語句進行查詢,此時Hibernate對其使用者物件進行了一級快取;當再次通過get()方法查詢時,Hibernate就不會發出SQL語句了,因為使用者名稱已經存在於一級快取中。程式執行結果:

Hibernate: 
select
user0_.id as id0_0_,
user0_.name as name0_0_,
user0_.sex as sex0_0_ 
from
tb_user_info user0_ 
where
user0_.id=?
使用者名稱:xqh
第二次查詢:
使用者名稱:xqh

注意:一級快取的生命週期與Session相對應,它並不會在Session之間共享,在不同的Session中不能得到其他Session中快取的實體物件

二級快取:

二級快取是SessionFactory級的快取,其生命週期與SessionFactory一致。二級快取可在多個Session間共享,屬於程序範圍或群集範圍的快取。

二級快取是一個可插拔的快取外掛,它的使用需要第三方快取產品的支援。在Hibernate框架中,通過Hibernate配置檔案配置二級快取的使用策略。

1.加入快取配置檔案ehcache.xml

<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="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.設定Hibernate配置檔案。


<!-- 開啟二級快取 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 指定快取產品提供商 -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<!-- 指定二級快取應用到的實體物件 -->
<class-cache class="com.xqh.model.User" usage="read-only"></class-cache>
例:
package com.xqh.util;
import org.hibernate.Session;
import com.xqh.model.User;
public class Test {
public static void main(String[] args) {
Session session = null; // 第一個Session
try {
session = HibernateUtil.getSession();
session.beginTransaction();
System.out.println("第一次查詢:");
User user = (User)session.get(User.class, 1);
System.out.println("使用者名稱:" + user.getName());
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
// 出錯將回滾事務
session.getTransaction().rollback();
} finally {
// 關閉Session物件
HibernateUtil.closeSession(session);
}
try {
session = HibernateUtil.getSession(); // 開啟第二個快取
session.beginTransaction();
System.out.println("第二次查詢:");
User user = (User)session.get(User.class, 1);
System.out.println("使用者名稱:" + user.getName());
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
// 出錯將回滾事務
session.getTransaction().rollback();
} finally {
// 關閉Session物件
HibernateUtil.closeSession(session);
}
}
}

二級快取在Session之間是共享的,因此可在不同Session中載入同一個物件,Hibernate將只發出一條SQL語句,當第二次載入物件時,Hibernate將從快取中獲取此物件。

程式結果:

第一次查詢:
Hibernate: 
select
user0_.id as id0_0_,
user0_.name as name0_0_,
user0_.sex as sex0_0_ 
from
tb_user_info user0_ 
where
user0_.id=?
使用者名稱:xqh
第二次查詢:
使用者名稱:xqh