1). 加入二級緩存插件的 jar 包及配置文件:
I. 複製 \hibernate-release-4.2.4.Final\lib\optional\ehcache\*.jar 到當前 Hibrenate 應用的類路徑下.
II. 複製 hibernate-release-4.2.4.Final\project\etc\ehcachexml 到當前 WEB 應用的類路徑下
2). 配置 hibernate.cfg.xml
I. 配置啓用 hibernate 的二級緩存
<property name="cache.use_second_level_cache">true</property>
II. 配置hibernate二級緩存使用的產品 <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
III. 配置對哪些類使用 hibernate 的二級緩存
<class-cache usage="read-write" class="com.atguigu.hibernate.entities.Employee"/>
實際上也可以在 .hbm.xml 文件中配置對哪些類使用二級緩存, 及二級緩存的策略是什麼.
2. 集合級別的二級緩存的配置I. 配置對集合使用二級緩存
<collection-cache usage="read-write" collection="com.atguigu.hibernate.entities.Department.emps"/>
也可以在 .hbm.xml 文件中進行配置
<set name="emps" table="GG_EMPLOYEE" inverse="true" lazy="true">
<cache usage="read-write"/>
<key>
<column name="DEPT_ID" />
</key>
<one-to-many class="com.atguigu.hibernate.entities.Employee" />
</set>
II. 注意: 還需要配置集合中的元素對應的持久化類也使用二級緩存! 否則將會多出 n 條 SQL 語句. 3. ehcache 的 配置文件: ehcache.xml
<!-- 指定一個目錄:當 EHCache 把數據寫到硬盤上時, 將把數據寫到這個目錄下.-->
<diskStore path="d:\\tempDirectory"/>,當SessionFactory關閉的時候,生成的文件會在指定的磁盤上清除。
<defaultCache
maxElementsInMemory="10000" 設置基於內存的緩存中可存放的對象最大數目
eternal="false" 設置對象是否爲永久的, true表示永不過期
timeToIdleSeconds="120" 設置對象空閒最長時間,以秒爲單位, 超過這個時間,對象過期
timeToLiveSeconds="120" 設置對象生存最長時間,超過這個時間,對象過期 ,如果此值爲0,表示對象可以無限期地存在於緩存中
overflowToDisk="true" 內存的緩存中的對象數目達到上限後,是否把溢出的對象寫到基於硬盤的緩存中
/>
<cache name="com.atguigu.hibernate.entities.Department.emps" 置緩存的名字,它的取值爲類的全限定名或類的集合的名字(集合的緩存策略,類名 . 屬性名)
maxElementsInMemory="1000"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/>
<cache name="com.atguigu.hibernate.entities.Employee" (類的緩存策略)
maxElementsInMemory="1"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
4. 查詢緩存: 默認情況下, 設置的緩存對 HQL 及 QBC 查詢時無效的, 但可以通過以下方式使其是有效的
I. 在 hibernate 配置文件中聲明開啓查詢緩存 <property name="cache.use_query_cache">true</property>
II. 調用 Query 或 Criteria 的 setCacheable(true) 方法
III. 查詢緩存依賴於二級緩存