Hibernate的緩存解讀
緩存是介于物理數(shù)據(jù)源與應(yīng)用程序之間,是對(duì)數(shù)據(jù)庫中的數(shù)據(jù)復(fù)制一份臨時(shí)放在內(nèi)存中的容器,其作用是為了減少應(yīng)用程序?qū)ξ锢頂?shù)據(jù)源訪問的次數(shù),從而提高了應(yīng)用的運(yùn)行性能。Hibernate在進(jìn)行讀取數(shù)據(jù)的時(shí)候,根據(jù)緩存機(jī)制在相應(yīng)的緩存中查詢,如果在緩存中找到了需要的數(shù)據(jù)(我們把這稱做“緩存命中"),則就直接把命中的數(shù)據(jù)作為結(jié)果加以利用,避免了大量發(fā)送SQL語句到數(shù)據(jù)庫查詢的性能損耗。
Hibernate緩存分類:
一、Session緩存(又稱作事務(wù)緩存):Hibernate內(nèi)置的,不能卸除。
緩存范圍:緩存只能被當(dāng)前Session對(duì)象訪問。緩存的生命周期依賴于Session的生命周期,當(dāng)Session被關(guān)閉后,緩存也就結(jié)束生命周期。
二、SessionFactory緩存(又稱作應(yīng)用緩存):使用第三方插件,可插拔。
緩存范圍:緩存被應(yīng)用范圍內(nèi)的所有session共享。這些session有可能是并發(fā)訪問緩存,因此必須對(duì)緩存進(jìn)行更新。緩存的生命周期依賴于應(yīng)用的生命周期,應(yīng)用結(jié)束時(shí),緩存也就結(jié)束了生命周期,二級(jí)緩存存在于應(yīng)用程序范圍。
Hibernate一些與一級(jí)緩存相關(guān)的操作(時(shí)間點(diǎn)):
數(shù)據(jù)放入緩存:
1. save()。當(dāng)session對(duì)象調(diào)用save()方法保存一個(gè)對(duì)象后,該對(duì)象會(huì)被放入到session的緩存中。
2. get()和load()。當(dāng)session對(duì)象調(diào)用get()或load()方法從數(shù)據(jù)庫取出一個(gè)對(duì)象后,該對(duì)象也會(huì)被放入到session的緩存中。
3. 使用HQL和QBC等從數(shù)據(jù)庫中查詢數(shù)據(jù)。
例如:數(shù)據(jù)庫有一張表如下:
使用get()或load()證明緩存的存在:
- public class Client
- {
- public static void main(String[] args)
- {
- Session session = HibernateUtil.getSessionFactory().openSession();
- Transaction tx = null;
- try
- {
- /*開啟一個(gè)事務(wù)*/
- tx = session.beginTransaction();
- /*從數(shù)據(jù)庫中獲取id="402881e534fa5a440134fa5a45340002"的Customer對(duì)象*/
- Customer customer1 = (Customer)session.get(Customer.class, "402881e534fa5a440134fa5a45340002");
- System.out.println("customer.getUsername is"+customer1.getUsername());
- /*事務(wù)提交*/
- tx.commit();
- System.out.println("-------------------------------------");
- /*開啟一個(gè)新事務(wù)*/
- tx = session.beginTransaction();
- /*從數(shù)據(jù)庫中獲取id="402881e534fa5a440134fa5a45340002"的Customer對(duì)象*/
- Customer customer2 = (Customer)session.get(Customer.class, "402881e534fa5a440134fa5a45340002");
- System.out.println("customer2.getUsername is"+customer2.getUsername());
- /*事務(wù)提交*/
- tx.commit();
- System.out.println("-------------------------------------");
- /*比較兩個(gè)get()方法獲取的對(duì)象是否是同一個(gè)對(duì)象*/
- System.out.println("customer1 == customer2 result is "+(customer1==customer2));
- }
- catch (Exception e)
- {
- if(tx!=null)
- {
- tx.rollback();
- }
- }
- finally
- {
- session.close();
- }
- }
- }
程序控制臺(tái)輸出結(jié)果:
- 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
輸出結(jié)果中只包含了一條SELECT SQL語句,而且customer1 == customer2 result is true說明兩個(gè)取出來的對(duì)象是同一個(gè)對(duì)象。其原理是:***次調(diào)用get()方法, Hibernate先檢索緩存中是否有該查找對(duì)象,發(fā)現(xiàn)沒有,Hibernate發(fā)送SELECT語句到數(shù)據(jù)庫中取出相應(yīng)的對(duì)象,然后將該對(duì)象放入緩存中,以便下次使用,第二次調(diào)用get()方法,Hibernate先檢索緩存中是否有該查找對(duì)象,發(fā)現(xiàn)正好有該查找對(duì)象,就從緩存中取出來,不再去數(shù)據(jù)庫中檢索。
數(shù)據(jù)從緩存中清除:
1. evit()將指定的持久化對(duì)象從緩存中清除,釋放對(duì)象所占用的內(nèi)存資源,指定對(duì)象從持久化狀態(tài)變?yōu)槊摴軤顟B(tài),從而成為游離對(duì)象。
2. clear()將緩存中的所有持久化對(duì)象清除,釋放其占用的內(nèi)存資源。
其他緩存操作:
1. contains()判斷指定的對(duì)象是否存在于緩存中。
2. flush()刷新緩存區(qū)的內(nèi)容,使之與數(shù)據(jù)庫數(shù)據(jù)保持同步。
Hibernate使用二級(jí)緩存
適合存放到第二級(jí)緩存中的數(shù)據(jù):
1. 很少被修改的數(shù)據(jù)。
2. 不是很重要的數(shù)據(jù),允許出現(xiàn)偶爾并發(fā)的數(shù)據(jù)。
3. 不會(huì)被并發(fā)訪問的數(shù)據(jù)。
4. 參考數(shù)據(jù),指的是供應(yīng)用參考的常量數(shù)據(jù),它的實(shí)例數(shù)目有限,它的實(shí)例會(huì)被許多其他類的實(shí)例引用,實(shí)例極少或者從來不會(huì)被修改。
不適合存放到第二級(jí)緩存的數(shù)據(jù):
1. 經(jīng)常被修改的數(shù)據(jù)。
2. 財(cái)務(wù)數(shù)據(jù),絕對(duì)不允許出現(xiàn)并發(fā)。
3. 與其他應(yīng)用共享的數(shù)據(jù)。
Hibernate如何將數(shù)據(jù)庫中的數(shù)據(jù)放入到二級(jí)緩存中?注意,你可以把緩存看做是一個(gè)Map對(duì)象,它的Key用于存儲(chǔ)對(duì)象OID,Value用于存儲(chǔ)POJO。首先,當(dāng)我們使用Hibernate從數(shù)據(jù)庫中查詢出數(shù)據(jù),獲取檢索的數(shù)據(jù)后,Hibernate將檢索出來的對(duì)象的OID放入緩存中key中,然后將具體的POJO放入value中,等待下一次再次向數(shù)據(jù)查詢數(shù)據(jù)時(shí),Hibernate根據(jù)你提供的OID先檢索一級(jí)緩存,若沒有且配置了二級(jí)緩存,則檢索二級(jí)緩存,如果還沒有則才向數(shù)據(jù)庫發(fā)送SQL語句,然后將查詢出來的對(duì)象放入緩存中。
為Hibernate配置二級(jí)緩存:
在主配置文件中hibernate.cfg.xml
- <property name="hibernate.cache.use_second_level_cache">true</property>
- <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
配置ehcache.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <ehcache>
- <!--
- 緩存到硬盤的路徑
- -->
- <diskStore path="d:/ehcache"></diskStore>
- <!--
- 默認(rèn)設(shè)置
- maxElementsInMemory : 在內(nèi)存中***緩存的對(duì)象數(shù)量。
- eternal : 緩存的對(duì)象是否永遠(yuǎn)不變。
- timeToIdleSeconds :可以操作對(duì)象的時(shí)間。
- timeToLiveSeconds :緩存中對(duì)象的生命周期,時(shí)間到后查詢數(shù)據(jù)會(huì)從數(shù)據(jù)庫中讀取。
- overflowToDisk :內(nèi)存滿了,是否要緩存到硬盤。
- -->
- <defaultCache maxElementsInMemory="200" eternal="false"
- timeToIdleSeconds="50" timeToLiveSeconds="60" overflowToDisk="true"></defaultCache>
- <!--
- 指定緩存的對(duì)象。
- 下面出現(xiàn)的的屬性覆蓋上面出現(xiàn)的,沒出現(xiàn)的繼承上面的。
- -->
- <cache name="com.suxiaolei.hibernate.pojos.Order" maxElementsInMemory="200" eternal="false"
- timeToIdleSeconds="50" timeToLiveSeconds="60" overflowToDisk="true"></cache>
- </ehcache>
在需要被緩存的對(duì)象中hbm文件中的<class>標(biāo)簽下添加一個(gè)<cache>子標(biāo)簽
- <hibernate-mapping>
- <class name="com.suxiaolei.hibernate.pojos.Order" table="orders">
- <cache usage="read-only"/>
- <id name="id" type="string">
- <column name="id"></column>
- <generator class="uuid"></generator>
- </id>
- <property name="orderNumber" column="orderNumber" type="string"></property>
- <property name="cost" column="cost" type="integer"></property>
- <many-to-one name="customer" class="com.suxiaolei.hibernate.pojos.Customer"
- column="customer_id" cascade="save-update">
- </many-to-one>
- </class>
- </hibernate-mapping>
若存在一對(duì)多的關(guān)系,想要在在獲取一方的時(shí)候?qū)㈥P(guān)聯(lián)的多方緩存起來,需要再集合屬性下添加<cache>子標(biāo)簽,這里需要將關(guān)聯(lián)的對(duì)象的hbm文件中必須在存在<class>標(biāo)簽下也添加<cache>標(biāo)簽,不然Hibernate只會(huì)緩存OID。
- <hibernate-mapping>
- <class name="com.suxiaolei.hibernate.pojos.Customer" table="customer">
- <!-- 主鍵設(shè)置 -->
- <id name="id" type="string">
- <column name="id"></column>
- <generator class="uuid"></generator>
- </id>
- <!-- 屬性設(shè)置 -->
- <property name="username" column="username" type="string"></property>
- <property name="balance" column="balance" type="integer"></property>
- <set name="orders" inverse="true" cascade="all" lazy="false" fetch="join">
- <cache usage="read-only"/>
- <key column="customer_id" ></key>
- <one-to-many class="com.suxiaolei.hibernate.pojos.Order"/>
- </set>
- </class>
- </hibernate-mapping>
原文鏈接:http://www.cnblogs.com/otomedaybreak/archive/2012/01/20/2328317.html
【編輯推薦】