Hibernate框架中的緩存技術詳解
本文實例講述了Hibernate框架中的緩存技術。分享給大家供大家參考,具體如下:
Hibernate框架的緩存分為Session的緩存、SessionFactory的緩存,也稱為一級緩存和二級緩存。
一級緩存:
一級緩存是Session級的緩存,其生命周期很短,與Session相互對應,由Hibernate進行管理,屬于事務范圍的緩存。當程序調用 Session的load()方法、get()方法、save()方法、saveOrUpdate()方法、update()方法或查詢接口方法時,Hibernate會對實體對象進行緩存;當通過load()方法或get()方法查詢實體對象時,Hibernate會首先到緩存中查詢,在找不到實體對像的情況下,Hibernate才會發(fā)出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會發(fā)出一條SQL語句進行查詢,此時Hibernate對其用戶對象進行了一級緩存;當再次通過get()方法查詢時,Hibernate就不會發(fā)出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將只發(fā)出一條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
對于二級緩存,可以使用一些不經常更新的數據或參考的數據,此時其性能會得到明顯的提升。但如果經常變化的數據應用二級緩存,則性能方面會造成一定問題。
希望本文所述對大家基于Hibernate框架的Java程序設計有所幫助。
相關文章
Spring Cloud OAuth2中/oauth/token的返回內容格式
Spring Cloud OAuth2 生成access token的請求/oauth/token的返回內容就需要自定義,本文就詳細介紹一下,感興趣的可以了解一下2021-07-07一天時間用Java寫了個飛機大戰(zhàn)游戲,朋友直呼高手
前兩天我發(fā)現論壇有兩篇飛機大戰(zhàn)的文章異?;鸨?但都是python寫的,竟然不是我大Java,說實話作為老java選手,我心里是有那么一些失落的,難道我大java打飛機不行?今天特地整理了這篇文章,需要的朋友可以參考下2021-05-05如何自定義Jackson序列化?@JsonSerialize
這篇文章主要介紹了如何自定義Jackson序列化?@JsonSerialize,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12Java之SpringBoot實現基本增刪改查(前后端分離版)
這篇文章主要介紹了Java中SpringBoot如何實現基本的增刪改查,前后端分離版,沒有和前端進行聯(lián)系,感興趣的小伙伴可以借鑒閱讀本文2023-03-03