1.导入ecache相关jar包,下载Jar
2.编写ecache.xml配置文件
<ehcache>
<!-- 指定一个文件目录,当EHCache把数据写到硬盘上时,将把数据写到这个目录下 -->
<diskStore path="D:\\ehcache"/>
<!--
设置缓存的默认数据过期策略
-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
<!--
name 设置缓存的名字,他的取值为类的完整名字或者类的集合的名字;
maxElementsInMemory 设置基于内存的缓存可存放的对象的最大数目
eternal 如果为true,表示对象永远不会过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds,默认为false;
timeToIdleSeconds 设定允许对象处于空闲状态的最长时间,以秒为单位;
timeToLiveSeconds 设定对象允许存在于缓存中的最长时间,以秒为单位;
overflowToDisk 如果为true,表示当基于内存的缓存中的对象数目达到maxElementsInMemory界限,会把溢出的对象写到基于硬盘的缓存中;
-->
<!-- 设定具体的第二级缓存的数据过期策略 -->
<cache name="entity.Product"
maxElementsInMemory="1"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
</ehcache>
3.编写hibernate.cfg.cml的配置文件
在内部进行配置:
需要添加的配置如下
<!-- 启用二级缓存 -->
<property name="cache.use_second_level_cache">true</property>
<!-- 配置使用的二级缓存的产品 -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- 配置启用查询缓存 -->
<property name="cache.use_query_cache">true</property>
完整配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.OracleDialect
</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:ORCL</property>
<property name="hibernate.connection.username">scott</property>
<property name="hibernate.connection.password">tiger</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- 最小连接数 -->
<property name="c3p0.min_size">7</property>
<!-- 最大连接数 -->
<property name="c3p0.max_size">42</property>
<!-- 获得连接的超时时间,如果超过这个时间,会抛出异常,单位毫秒 -->
<property name="c3p0.timeout">1800</property>
<!-- 最大的PreparedStatement的数量 -->
<property name="c3p0.max_statements">50</property>
<!-- 启用二级缓存 -->
<property name="cache.use_second_level_cache">true</property>
<!-- 配置使用的二级缓存的产品 -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- 配置启用查询缓存 -->
<property name="cache.use_query_cache">true</property>
<mapping class="entity.Product" />
</session-factory>
</hibernate-configuration>