Hibernate 二级缓存---ehcache的使用

hibernate的二级缓存也称进程级的缓存或SessionFactory级的缓存,可以被所有的session共享,生命周期同SessionFactory生命周期相同,SessionFactory可以管理二级缓存。

hibernate二级缓存介绍:
* 实现为可插拔,通过修改hibernate.cfg.xml文件中的cache.provider_class参数来指定不同的cache生成商并使用。

* 指定要缓存的对象并制定使用的缓存策略方式(两种):
1.在hibernate.cfg.xml文件中加入<class-cache class="com.yx.zzg.Student" usage="read-only" />
2.在映射文件中主键生成策略前家入<cache usage="read-only" />
其中usage包含read-only,read-write,nonstrict-read-write,transactional几个参数

* Session的:save(这个方法不适合native生成方式的主键,如果为native则不会放入二级缓存中),update,saveOrUpdate,list,iterator,get,load以及Query,Criteria都会填充二级缓存,但只有(没有打开查询缓存时),Session的iterator,get,load会从二级缓存中取数据(iterator可能存在N+1次查询)。

* Query,Criteria(查询缓存)由于命中率较低,所以hibernate缺省是关闭;需要在hibernate.cfg.xml文件中设置cache.use_query_cache为true打开查询缓存,并且在方法中需要显示的调用query.setCacheable(true);或criteria.setCacheable(true);

* SessionFactory中提供了evictXXX()方法用来清除缓存中的内容

* 打开统计信息需要在hibernate.cfg.xml中设置generate_statistics为true,用sessionFactory.getStatistics()获取统计信息,该统计信息对于调试非常有用。


1、创建一个java项目,并加入Hibernate的依赖库。
[quote]
* Hibernate_HOME/hibernate3.jar
* Hibernate_HOME/lib/*.jar
[/quote]
2、编写两个实体类

package com.yx.zzg;

import java.util.Set;

public class Classes {
private int id;
private String name;
private Set students;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set getStudents() {
return students;
}
public void setStudents(Set students) {
this.students = students;
}
}


package com.yx.zzg;

public class Student {
private int id;
private String name;
private Classes classes;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Classes getClasses() {
return classes;
}
public void setClasses(Classes classes) {
this.classes = classes;
}
}

3、编写两个实体类的映射文件
Classes.hbm.xml文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.yx.zzg">
<class name="Classes" table="t_classes">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<set name="students" inverse="true" cascade="all">
<key column="classesid"/>
<one-to-many class="Student"/>
</set>
</class>
</hibernate-mapping>

Student.hbm.xml文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.yx.zzg.Student" table="t_student">
<!--指定该类需要缓存,并指定缓存策略-->
<!--
<cache usage="read-only" />
-->
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<many-to-one name="classes" column="classesid"/>
</class>
</hibernate-mapping>

4、在src目录下加入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>

5、编写Hibernate配置文件

<!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">123456</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/yx/zzg/Classes.hbm.xml"/>
<mapping resource="com/yx/zzg/Student.hbm.xml"/>

<!-- 指定要被缓存的类并设置缓存策略 -->
<class-cache class="com.yx.zzg.Student" usage="read-only" />
</session-factory>
</hibernate-configuration>

注:OSCache的使用同理!二级缓存是缓存实体对象的,对于非实体对象(如具体属性)则是不能缓存的!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值