二级缓存也称进程级的缓存或SessionFactory级的缓存,二级缓存可以被所有的session共享
二级缓存的生命周期和SessionFactory的生命周期一致,SessionFactory可以管理二级缓存
二级缓存的配置和使用:
* 将echcache.xml文件拷贝到src下
* 开启二级缓存,修改hibernate.cfg.xml文件
<property name="hibernate.cache.use_second_level_cache">true</property>
* 指定缓存产品提供商,修改hibernate.cfg.xml文件
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
* 指定那些实体类使用二级缓存(两种方法)
* 在映射文件中采用<cache>标签
* 在hibernate.cfg.xml文件中,采用<class-cache>标签
二级缓存是缓存实体对象的
了解一级缓存和二级缓存的交互
代码如下:
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>
<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>
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernate_cache</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">bjsxt</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<!-- 开启二级缓存
-->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 指定缓存产品提供商
-->
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<mapping resource="com/bjsxt/hibernate/Classes.hbm.xml" />
<mapping resource="com/bjsxt/hibernate/Student.hbm.xml" />
<class-cache class="com.bjsxt.hibernate.Student" usage="read-only" include="all" />
</session-factory>
</hibernate-configuration>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernate_cache</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">bjsxt</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<!-- 开启二级缓存
-->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 指定缓存产品提供商
-->
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<mapping resource="com/bjsxt/hibernate/Classes.hbm.xml" />
<mapping resource="com/bjsxt/hibernate/Student.hbm.xml" />
<class-cache class="com.bjsxt.hibernate.Student" usage="read-only" include="all" />
</session-factory>
</hibernate-configuration>
测试code
1package com.bjsxt.hibernate;
2
3import java.io.Serializable;
4
5import org.hibernate.CacheMode;
6import org.hibernate.Session;
7import org.hibernate.SessionFactory;
8
9import junit.framework.TestCase;
10
11public class CacheLevel2Test extends TestCase {
12
13 /** *//**
14 * 开启两个session,分别调用load
15 */
16 public void testCache1() {
17 Session session = null;
18 try {
19 session = HibernateUtils.getSession();
20 session.beginTransaction();
21
22 Student student = (Student)session.load(Student.class, 1);
23 System.out.println("student.name=" + student.getName());
24
25 session.getTransaction().commit();
26 }catch(Exception e) {
27 e.printStackTrace();
28 session.getTransaction().rollback();
29 }finally {
30 HibernateUtils.closeSession(session);
31 }
32
33 try {
34 session = HibernateUtils.getSession();
35 session.beginTransaction();
36
37 //不会发出sql,因为开启了二级缓存,session是共享二级缓存的
38 Student student = (Student)session.load(Student.class, 1);
39 System.out.println("student.name=" + student.getName());
40
41 session.getTransaction().commit();
42 }catch(Exception e) {
43 e.printStackTrace();
44 session.getTransaction().rollback();
45 }finally {
46 HibernateUtils.closeSession(session);
47 }
48
49 }
50
51 /** *//**
52 * 开启两个session,分别调用get
53 */
54 public void testCache2() {
55 Session session = null;
56 try {
57 session = HibernateUtils.getSession();
58 session.beginTransaction();
59
60 Student student = (Student)session.get(Student.class, 1);
61 System.out.println("student.name=" + student.getName());
62
63 session.getTransaction().commit();
64 }catch(Exception e) {
65 e.printStackTrace();
66 session.getTransaction().rollback();
67 }finally {
68 HibernateUtils.closeSession(session);
69 }
70
71 try {
72 session = HibernateUtils.getSession();
73 session.beginTransaction();
74
75 //不会发出sql,因为开启了二级缓存,session是共享二级缓存的
76 Student student = (Student)session.get(Student.class, 1);
77 System.out.println("student.name=" + student.getName());
78
79 session.getTransaction().commit();
80 }catch(Exception e) {
81 e.printStackTrace();
82 session.getTransaction().rollback();
83 }finally {
84 HibernateUtils.closeSession(session);
85 }
86 }
87
88 /** *//**
89 * 开启两个session,分别调用load,在使用SessionFactory清除二级缓存
90 */
91 public void testCache3() {
92 Session session = null;
93 try {
94 session = HibernateUtils.getSession();
95 session.beginTransaction();
96
97 Student student = (Student)session.load(Student.class, 1);
98 System.out.println("student.name=" + student.getName());
99
100 session.getTransaction().commit();
101 }catch(Exception e) {
102 e.printStackTrace();
103 session.getTransaction().rollback();
104 }finally {
105 HibernateUtils.closeSession(session);
106 }
107
108 //管理二级缓存
109 SessionFactory factory = HibernateUtils.getSessionFactory();
110 //factory.evict(Student.class);
111 factory.evict(Student.class, 1);
112
113 try {
114 session = HibernateUtils.getSession();
115 session.beginTransaction();
116
117 //会发出查询sql,因为二级缓存中的数据被清除了
118 Student student = (Student)session.load(Student.class, 1);
119 System.out.println("student.name=" + student.getName());
120
121 session.getTransaction().commit();
122 }catch(Exception e) {
123 e.printStackTrace();
124 session.getTransaction().rollback();
125 }finally {
126 HibernateUtils.closeSession(session);
127 }
128 }
129
130
131 /** *//**
132 * 一级缓存和二级缓存的交互
133 */
134 public void testCache4() {
135 Session session = null;
136 try {
137 session = HibernateUtils.getSession();
138 session.beginTransaction();
139
140 //仅向二级缓存读数据,而不向二级缓存写数据
141 session.setCacheMode(CacheMode.GET);
142 Student student = (Student)session.load(Student.class, 1);
143 System.out.println("student.name=" + student.getName());
144
145 session.getTransaction().commit();
146 }catch(Exception e) {
147 e.printStackTrace();
148 session.getTransaction().rollback();
149 }finally {
150 HibernateUtils.closeSession(session);
151 }
152
153 try {
154 session = HibernateUtils.getSession();
155 session.beginTransaction();
156
157 //发出sql语句,因为session设置了CacheMode为GET,所以二级缓存中没有数据
158 Student student = (Student)session.load(Student.class, 1);
159 System.out.println("student.name=" + student.getName());
160
161 session.getTransaction().commit();
162 }catch(Exception e) {
163 e.printStackTrace();
164 session.getTransaction().rollback();
165 }finally {
166 HibernateUtils.closeSession(session);
167 }
168
169 try {
170 session = HibernateUtils.getSession();
171 session.beginTransaction();
172
173 //只向二级缓存写数据,而不从二级缓存读数据
174 session.setCacheMode(CacheMode.PUT);
175
176 //会发出查询sql,因为session将CacheMode设置成了PUT
177 Student student = (Student)session.load(Student.class, 1);
178 System.out.println("student.name=" + student.getName());
179
180 session.getTransaction().commit();
181 }catch(Exception e) {
182 e.printStackTrace();
183 session.getTransaction().rollback();
184 }finally {
185 HibernateUtils.closeSession(session);
186 }
187
188 }
189}
190
1package com.bjsxt.hibernate;
2
3import java.io.Serializable;
4
5import org.hibernate.CacheMode;
6import org.hibernate.Session;
7import org.hibernate.SessionFactory;
8
9import junit.framework.TestCase;
10
11public class CacheLevel2Test extends TestCase {
12
13 /** *//**
14 * 开启两个session,分别调用load
15 */
16 public void testCache1() {
17 Session session = null;
18 try {
19 session = HibernateUtils.getSession();
20 session.beginTransaction();
21
22 Student student = (Student)session.load(Student.class, 1);
23 System.out.println("student.name=" + student.getName());
24
25 session.getTransaction().commit();
26 }catch(Exception e) {
27 e.printStackTrace();
28 session.getTransaction().rollback();
29 }finally {
30 HibernateUtils.closeSession(session);
31 }
32
33 try {
34 session = HibernateUtils.getSession();
35 session.beginTransaction();
36
37 //不会发出sql,因为开启了二级缓存,session是共享二级缓存的
38 Student student = (Student)session.load(Student.class, 1);
39 System.out.println("student.name=" + student.getName());
40
41 session.getTransaction().commit();
42 }catch(Exception e) {
43 e.printStackTrace();
44 session.getTransaction().rollback();
45 }finally {
46 HibernateUtils.closeSession(session);
47 }
48
49 }
50
51 /** *//**
52 * 开启两个session,分别调用get
53 */
54 public void testCache2() {
55 Session session = null;
56 try {
57 session = HibernateUtils.getSession();
58 session.beginTransaction();
59
60 Student student = (Student)session.get(Student.class, 1);
61 System.out.println("student.name=" + student.getName());
62
63 session.getTransaction().commit();
64 }catch(Exception e) {
65 e.printStackTrace();
66 session.getTransaction().rollback();
67 }finally {
68 HibernateUtils.closeSession(session);
69 }
70
71 try {
72 session = HibernateUtils.getSession();
73 session.beginTransaction();
74
75 //不会发出sql,因为开启了二级缓存,session是共享二级缓存的
76 Student student = (Student)session.get(Student.class, 1);
77 System.out.println("student.name=" + student.getName());
78
79 session.getTransaction().commit();
80 }catch(Exception e) {
81 e.printStackTrace();
82 session.getTransaction().rollback();
83 }finally {
84 HibernateUtils.closeSession(session);
85 }
86 }
87
88 /** *//**
89 * 开启两个session,分别调用load,在使用SessionFactory清除二级缓存
90 */
91 public void testCache3() {
92 Session session = null;
93 try {
94 session = HibernateUtils.getSession();
95 session.beginTransaction();
96
97 Student student = (Student)session.load(Student.class, 1);
98 System.out.println("student.name=" + student.getName());
99
100 session.getTransaction().commit();
101 }catch(Exception e) {
102 e.printStackTrace();
103 session.getTransaction().rollback();
104 }finally {
105 HibernateUtils.closeSession(session);
106 }
107
108 //管理二级缓存
109 SessionFactory factory = HibernateUtils.getSessionFactory();
110 //factory.evict(Student.class);
111 factory.evict(Student.class, 1);
112
113 try {
114 session = HibernateUtils.getSession();
115 session.beginTransaction();
116
117 //会发出查询sql,因为二级缓存中的数据被清除了
118 Student student = (Student)session.load(Student.class, 1);
119 System.out.println("student.name=" + student.getName());
120
121 session.getTransaction().commit();
122 }catch(Exception e) {
123 e.printStackTrace();
124 session.getTransaction().rollback();
125 }finally {
126 HibernateUtils.closeSession(session);
127 }
128 }
129
130
131 /** *//**
132 * 一级缓存和二级缓存的交互
133 */
134 public void testCache4() {
135 Session session = null;
136 try {
137 session = HibernateUtils.getSession();
138 session.beginTransaction();
139
140 //仅向二级缓存读数据,而不向二级缓存写数据
141 session.setCacheMode(CacheMode.GET);
142 Student student = (Student)session.load(Student.class, 1);
143 System.out.println("student.name=" + student.getName());
144
145 session.getTransaction().commit();
146 }catch(Exception e) {
147 e.printStackTrace();
148 session.getTransaction().rollback();
149 }finally {
150 HibernateUtils.closeSession(session);
151 }
152
153 try {
154 session = HibernateUtils.getSession();
155 session.beginTransaction();
156
157 //发出sql语句,因为session设置了CacheMode为GET,所以二级缓存中没有数据
158 Student student = (Student)session.load(Student.class, 1);
159 System.out.println("student.name=" + student.getName());
160
161 session.getTransaction().commit();
162 }catch(Exception e) {
163 e.printStackTrace();
164 session.getTransaction().rollback();
165 }finally {
166 HibernateUtils.closeSession(session);
167 }
168
169 try {
170 session = HibernateUtils.getSession();
171 session.beginTransaction();
172
173 //只向二级缓存写数据,而不从二级缓存读数据
174 session.setCacheMode(CacheMode.PUT);
175
176 //会发出查询sql,因为session将CacheMode设置成了PUT
177 Student student = (Student)session.load(Student.class, 1);
178 System.out.println("student.name=" + student.getName());
179
180 session.getTransaction().commit();
181 }catch(Exception e) {
182 e.printStackTrace();
183 session.getTransaction().rollback();
184 }finally {
185 HibernateUtils.closeSession(session);
186 }
187
188 }
189}
190