本文執行個體講述了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(); // 擷取sessionsession.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: selectuser0_.id as id0_0_,user0_.name as name0_0_,user0_.sex as sex0_0_ fromtb_user_info user0_ whereuser0_.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 byits value in the running VM.The following properties are translated:user.home - User's home directoryuser.dir - User's current working directoryjava.io.tmpdir - Default temp file path --><diskStore path="java.io.tmpdir"/><!--Default Cache configuration. These will applied to caches programmatically created throughthe CacheManager.The following attributes are required for defaultCache:maxInMemory - Sets the maximum number of objects that will be created in memoryeternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the elementis never expired.timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only usedif the element is not eternal. Idle time is now - last accessed timetimeToLiveSeconds - Sets the time to live for an element before it expires. Is only usedif the element is not eternal. TTL is now - creation timeoverflowToDisk - Sets whether elements can overflow to disk when the in-memory cachehas reached the maxInMemory limit.--><defaultCachemaxElementsInMemory="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 theCacheManager startsThe 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 memoryeternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the elementis never expired.timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only usedif the element is not eternal. Idle time is now - last accessed timetimeToLiveSeconds - Sets the time to live for an element before it expires. Is only usedif the element is not eternal. TTL is now - creation timeoverflowToDisk - Sets whether elements can overflow to disk when the in-memory cachehas reached the maxInMemory limit.--><!-- Sample cache named sampleCache1This cache contains a maximum in memory of 10000 elements, and will expirean element if it is idle for more than 5 minutes and lives for more than10 minutes.If there are more than 10000 elements it will overflow to thedisk cache, which in this configuration will go to wherever java.io.tmp isdefined 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 sampleCache2This 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; // 第一個Sessiontry {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: selectuser0_.id as id0_0_,user0_.name as name0_0_,user0_.sex as sex0_0_ fromtb_user_info user0_ whereuser0_.id=?使用者名稱:xqh第二次查詢:使用者名稱:xqh
對於二級緩衝,可以使用一些不經常更新的資料或參考的資料,此時其效能會得到明顯的提升。但如果經常變化的資料應用二級緩衝,則效能方面會造成一定問題。
希望本文所述對大家基於Hibernate架構的Java程式設計有所協助。