首先整理一下hibernate中關(guān)于緩存的知識點
- 一級緩存
僅當前事物能夠訪問恭垦,如果事務(wù)結(jié)束每币,則緩存也會結(jié)束
evict()將某對象從一級緩存中清除
clear()將一級緩存中的所有對象清除
get()/load()都支持一級緩存的讀和寫
save()方法會將持久化的對象放入session奔穿,如果有大量數(shù)據(jù)需要保存則應(yīng)該使用批處理的方式進行保存
一級緩存被設(shè)置為內(nèi)置且不可卸載,無需任何配置即可使用- 二級緩存
該緩存可以被應(yīng)用中的所有事務(wù)訪問,只有當應(yīng)用結(jié)束,緩存的生命周期才會結(jié)束
二級緩存對應(yīng)的是sessionFactory級別巫俺,所以允許多個session之間共用
二級緩存默認是關(guān)閉的,需要在hibernate.cfg.xml中進行配置
打開二級緩存
<property name="hibernate.cache.use_second_level_cache">true</property>
指定緩存提供者
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.internal.SingletonEhcacheRegionFactory</property>
- 查詢緩存
查詢緩存依賴于二級緩存肿男,可以理解為二級緩存的加強版
打開查詢緩存
<property name="hibernate.cache.use_query_cache">true</property>
如果要使用查詢緩存則需要對其進行啟用
query.setCacheable(true)
如果用的是注解方式則需要在類上加上一個@Cacheable
只有當HQL查詢語句完全相同時介汹,查詢緩存才會生效
使用查詢緩存時必須開啟二級緩存否則會引起N+1問題
1. Ehcache的配置
需要使用到的額外的jar包 hibernate-ehcache.jar
slf4j-api.jar
ehcache-core.jar
在使用jar包時却嗡,注意版本是否支持
2. 編寫ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!-- 設(shè)置硬盤目錄 -->
<diskStore path="D:\\temp"/>
<!-- maxElementsInMemory 緩存最大個數(shù) -->
<!-- eternal 是否永久有效,如果該值設(shè)置為true,則timeout將失效 -->
<!-- timeToIdleSeconds 失效前的閑置時間 -->
<!-- timeToLiveSeconds 失效前的存活時間 -->
<!-- diskSpoolBufferSizeMB 緩存區(qū)的大小 默認30M -->
<!-- maxElementsOnDisk 硬盤最大緩存?zhèn)€數(shù) -->
<!-- overflowToDisk 超出緩存最大個數(shù)時寫入硬盤 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
</ehcache>
3. 對應(yīng)的配置
如果是XML
的方式則需要在hibernate.cfg.xml
中加入以下配置
<class-cache class="pojo.User" usage="read-write"/>
如果是注解的方式則需要在類中加入以下注解
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
ehcache.xml
這個文件會在應(yīng)用啟動時被加載所以需不要額外的配置
好了,Ehcache就已經(jīng)整合完畢了