標籤:cascade .sh nat elements str where 內容 jar spring配置
1.什麼是緩衝?
緩衝是介於物理資料來源與應用程式之間,是對資料庫中的資料複製一份臨時放在記憶體中的容器,其作用是為了減少應用程式對物理資料來源訪問的次數,從而提高了應用程式的運行效能。Hibernate在進行讀取資料的時候,根據緩衝機制在相應的緩衝中查詢,如果在緩衝中找到了需要的資料(我們把這稱做“緩衝命 中"),則就直接把命中的資料作為結果加以利用,避免了大量發送SQL語句到資料庫查詢的效能損耗。
緩衝策略供應商:
提供了HashTable緩衝,EHCache,OSCache,SwarmCache,jBoss Cathe2,這些緩衝機制,其中EHCache,OSCache是不能用於叢集環境(Cluster Safe)的,而SwarmCache,jBoss Cathe2是可以的。HashTable緩衝主要是用來測試的,只能把對象放在記憶體中,EHCache,OSCache可以把對象放在記憶體(memory)中,也可以把對象放在硬碟(disk)上(為什麼放到硬碟上?上面解釋了)。
Hibernate緩衝分類:
一、Session緩衝(又稱作事務緩衝):Hibernate內建的,不能卸載。
緩衝範圍:緩衝只能被當前Session對象訪問。緩衝的生命週期依賴於Session的生命週期,當Session被關閉後,緩衝也就結束生命週期。
二、SessionFactory緩衝(又稱作應用緩衝):使用第三方外掛程式,可插拔。
緩衝範圍:緩衝被應用範圍內的所有session共用,不同的Session可以共用。這些session有可能是並發訪問緩衝,因此必須對緩衝進行更新。緩衝的生命週期依賴於應用的生命週期,應用結束時,緩衝也就結束了生命週期,二級緩衝存在於應用程式範圍。
一級緩衝:
Hibernate一些與一級緩衝相關的操作(時間點):
資料放入緩衝:
1. save()。當session對象調用save()方法儲存一個對象後,該對象會被放入到session的緩衝中。
2. get()和load()。當session對象調用get()或load()方法從資料庫取出一個對象後,該對象也會被放入到session的緩衝中。
3. 使用HQL和QBC等從資料庫中查詢資料。
例如:資料庫有一張表如下:
使用get()或load()證明緩衝的存在:
public class Client
{ public static void main(String[] args)
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null; try
{ /*開啟一個事務*/
tx = session.beginTransaction(); /*從資料庫中擷取id="402881e534fa5a440134fa5a45340002"的Customer對象*/
Customer customer1 = (Customer)session.get(Customer.class, "402881e534fa5a440134fa5a45340002");
System.out.println("customer.getUsername is"+customer1.getUsername()); /*事務提交*/
tx.commit();
System.out.println("-------------------------------------");
/*開啟一個新事務*/
tx = session.beginTransaction(); /*從資料庫中擷取id="402881e534fa5a440134fa5a45340002"的Customer對象*/
Customer customer2 = (Customer)session.get(Customer.class, "402881e534fa5a440134fa5a45340002");
System.out.println("customer2.getUsername is"+customer2.getUsername()); /*事務提交*/
tx.commit();
System.out.println("-------------------------------------");
/*比較兩個get()方法擷取的對象是否是同一個對象*/
System.out.println("customer1 == customer2 result is "+(customer1==customer2));
} catch (Exception e)
{ if(tx!=null)
{
tx.rollback();
}
} finally
{
session.close();
}
}
}
程式控制台輸出結果:
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
其原理是:在同一個Session裡面,第一次調用get()方法, Hibernate先檢索緩衝中是否有該尋找對象,發現沒有,Hibernate發送SELECT語句到資料庫中取出相應的對象,然後將該對象放入緩衝中,以便下次使用,第二次調用get()方法,Hibernate先檢索緩衝中是否有該尋找對象,發現正好有該尋找對象,就從緩衝中取出來,不再去資料庫中檢索,沒有再次發送select語句。
資料從緩衝中清除:
1. evit()將指定的持久化對象從緩衝中清除,釋放對象所佔用的記憶體資源,指定對象從持久化狀態變為脫管狀態,從而成為游離對象。
2. clear()將緩衝中的所有持久化對象清除,釋放其佔用的記憶體資源。
其他快取作業:
1. contains()判斷指定的對象是否存在於緩衝中。
2. flush()重新整理緩衝區的內容,使之與資料庫資料保持同步。
二級緩衝:
@Testpublic void testCache2() {
Session session1 = sf.openSession();//獲得Session1session1.beginTransaction();
Category c = (Category)session1.load(Category.class, 1);
System.out.println(c.getName());
session1.getTransaction().commit();
session1.close();
Session session2 = sf.openSession();//獲得Session2session2.beginTransaction();
Category c2 = (Category)session2.load(Category.class, 1);
System.out.println(c2.getName());
session2.getTransaction().commit();
session2.close();
}
當我們重啟一個Session,第二次調用load或者get方法檢索同一個對象的時候會重新尋找資料庫,會發select語句資訊。
原因:一個session不能取另一個session中的緩衝。
效能上的問題:假如是多線程同時去取Category這個對象,load一個對象,這個對像本來可以放到記憶體中的,可是由於是多線程,是分布在不同的session當中的,所以每次都要從資料庫中取,這樣會帶來查詢效能較低的問題。
解決方案:使用二級緩衝。
1.什麼是二級緩衝?
SessionFactory層級的緩衝,可以跨越Session存在,可以被多個Session所共用。
2.適合放到二級緩衝中:
(1)經常被訪問
(2)改動不大
(3)數量有限
(4)不是很重要的資料,允許出現偶爾並發的資料。
這樣的資料非常適合放到二級緩衝中的。
使用者的許可權:使用者的數量不大,許可權不多,不會經常被改動,經常被訪問。
例如組織機構。
思考:什麼樣的類,裡面的對象才適合放到二級緩衝中?
改動頻繁,類裡面對象特別多,BBS好多文章,這些文章20000多條,哪些放到緩衝中,不能確定。除非你確定有一些經常被訪問的,資料量並不大,改動非常少,這樣的資料非常適合放到二級緩衝中的。
3.二級緩衝實現原理:
Hibernate如何將資料庫中的資料放入到二級緩衝中?注意,你可以把緩衝看做是一個Map對象,它的Key用於儲存物件OID,Value用於儲存POJO。首先,當我們使用Hibernate從資料庫中查詢出資料,擷取檢索的資料後,Hibernate將檢索出來的對象的OID放入緩衝中key 中,然後將具體的POJO放入value中,等待下一次再次向資料查詢資料時,Hibernate根據你提供的OID先檢索一級緩衝,若有且配置了二級緩衝,則檢索二級緩衝,如果還沒有則才向資料庫發送SQL語句,然後將查詢出來的對象放入緩衝中。
4.使用二級緩衝
(1)開啟二級緩衝:
為Hibernate配置二級緩衝:
在主設定檔中hibernate.cfg.xml :
<!-- 使用二級緩衝 -->
<!-- 使用二級緩衝 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!--設定緩衝的類型,設定緩衝的供應商-->
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
或者當hibernate與Spring整合後直接配到Spring設定檔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)配置ehcache.xml
<?xml version="1.0" encoding="UTF-8"?><ehcache>
<!--
緩衝到硬碟的路徑 -->
<diskStore path="d:/ehcache"></diskStore>
<!--
預設設定
maxElementsInMemory : 在內存中最大緩存的對象數量。
eternal : 緩衝的對象是否永遠不變。
timeToIdleSeconds :可以操作對象的時間。
timeToLiveSeconds :緩衝中對象的生命週期,時間到後查詢資料會從資料庫中讀取。
overflowToDisk :記憶體滿了,是否要緩衝到硬碟。 -->
<defaultCache maxElementsInMemory="200" eternal="false"
timeToIdleSeconds="50" timeToLiveSeconds="60" overflowToDisk="true"></defaultCache>
<!--
指定緩衝的對象。
下面出現的的屬性覆蓋上面出現的,沒出現的繼承上面的。 -->
<cache name="com.suxiaolei.hibernate.pojos.Order" maxElementsInMemory="200" eternal="false"
timeToIdleSeconds="50" timeToLiveSeconds="60" overflowToDisk="true"></cache></ehcache>
(3)使用二級緩衝需要在實體類中加入註解:
需要ehcache-1.2.3.jar包:
還需要 commons_loging1.1.1.jar包
在實體類中通過註解可以配置實用二級緩衝:
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
Load預設使用二級緩衝,就是當查一個對象的時候,它先會去二級緩衝裡面去找,如果找到了就不去資料庫中查了。
Iterator預設的也會使用二級緩衝,有的話就不去資料庫裡面查了,不發送select語句了。
List預設的往二級緩衝中加資料,假如有一個query,把資料拿出來之後會放到二級緩衝,但是執行查詢的時候不會到二級緩衝中查,會在資料庫中查。原因每個query中查詢條件不一樣。
(4)也可以在需要被緩衝的對象中hbm檔案中的<class>標籤下添加一個<cache>子標籤:
<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>
存在一對多的關係,想要在在擷取一方的時候將關聯的多方緩衝起來,需要再集合屬性下添加<cache>子標籤,這裡需要將關聯的對象的 hbm檔案中必須在存在<class>標籤下也添加<cache>標籤,不然Hibernate只會緩衝OID。
<hibernate-mapping>
<class name="com.suxiaolei.hibernate.pojos.Customer" table="customer">
<!-- 主鍵設定 -->
<id name="id" type="string">
<column name="id"></column>
<generator class="uuid"></generator>
</id>
<!-- 屬性設定 -->
<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>
hibernate......1、2級緩衝