程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Hibernate框架中的緩存技巧詳解

Hibernate框架中的緩存技巧詳解

編輯:關於JAVA

Hibernate框架中的緩存技巧詳解。本站提示廣大學習愛好者:(Hibernate框架中的緩存技巧詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是Hibernate框架中的緩存技巧詳解正文


本文實例講述了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(); // 獲得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會收回一條SQL語句停止查詢,此時Hibernate對其用戶對象停止了一級緩存;當再次經由過程get()辦法查詢時,Hibernate就不會收回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將只收回一條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法式設計有所贊助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved