1 首先导入第三方的jar包 ehcache-1.2.3.jar
2 在src文件夹下面添加ehcache.xml 内容如下:
<?xml version='1.0' encoding='GBK'?>
<ehcache>
<!--缓存数据的路径-->
<diskStore path="D:/hibernateTem"/>
<!--默认的缓存配置,用在当没有配置针对某个对象的缓存时,采用默认的配置-->
<!--eternal缓存的某个对象是否是永恒的。当它值是true时,timeToIdleSeconds和timeToLiveSeconds的值都无效-->
<!--maxElementsInMemory内存中缓存某个对象的最大个数-->
<!--timeToIdleSeconds容许某个对象在缓存中空闲的最大时间,超过这个时间自动从缓存中清除 当值是0的时候,表示无限长-->
<!--timeToLiveSeconds容许某个对象在缓存中缓存的最大时间,超过这个时间自动从缓存中清除 当值是0的时候,表示无限长-->
<overflowToDisk当缓存某个对象的数量超过maxElementsInMemory的值时,是否写入磁盘文件-->
<defaultCache
maxElementsInMemory="10"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="240"
overflowToDisk="true"
/>
//批注:在<class name="pojo.Type" table="type">结点中加<cache usage="read-write"/>
<cache name="pojo.Type"
maxElemntsInMomory="1"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
//在<set name="images"...>结点中加入<cache usage="read-write"/>
<cache name="pojo.Type.images"
maxElementsInMemory="2"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
</ehcache>
修改Hibernate.cfg.xml
3 开启缓存 默认就是开启的
<property name="hibernate.cache.use_second level_cache">true</property>
4 在配置文件中加入如下配置:
<class>
<cache usage="read-write"/>
<id></id>
<class>
或者在Hibernate.cfg.xml<mapping>节点的后面
<class-cache class="全路径名" usage="read-only">
对于<cache usage="read-write"/>
为了使得缓存调度遵循正确的应用级事务隔离机制,必须为每个实体类指定相应的缓存同步策略
Read-only 只读 对于不会发生改变的数据,可以使用只读型缓存
Nonstrict-read-only 数据更新频率较低时使用
Read-write 严格读写缓存,用于对数据同步要求严格的情况
Transactional 事务型缓存,必须运行在JTA环境