本文實例講述了Hibernate框架中的緩存技術。分享給大家供大家參考,具體如下:
Hibernate框架的緩存分為Session的緩存、SessionFactory的緩存,也稱為一級緩存和二級緩存。
一級緩存:
一級緩存是Session級的緩存,其生命周期很短,與Session相互對應,由Hibernate進行管理,屬于事務范圍的緩存。當程序調用 Session的load()方法、get()方法、save()方法、saveOrUpdate()方法、update()方法或查詢接口方法時,Hibernate會對實體對象進行緩存;當通過load()方法或get()方法查詢實體對象時,Hibernate會首先到緩存中查詢,在找不到實體對像的情況下,Hibernate才會發出SQL語句到數據庫中查詢,從而提高了Hibernate的使用效率。
舉個例子來說吧:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
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語句了,因為用戶名已經存在于一級緩存中。程序運行結果:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
第一次查詢: 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
< 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配置文件。
1
2
3
4
5
6
|
<!-- 開啟二級緩存 --> < 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 > |
例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
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將從緩存中獲取此對象。
程序結果:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
第一次查詢: 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程序設計有所幫助。