Hibernate二级缓存

来源:互联网 发布:淘宝 设计师 编辑:程序博客网 时间:2024/06/14 19:52

适合放入二级缓存的数据有如下特性:

i.经常被访问;

ii.改动不大,不会经常改动;

iii.数量有限

需要加入的jar包:ehcache-1.3.0.jar,commons-logging-1.1.1.jar。(版本变动可能会带来一些其他问题,管理jar包还是使用maven方便)

1.在Hibernate.cfg.xml中添加如下内容:

<property name="hibernate.cache.use_second_level_cache">true</property><property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>

2.引入ehcache.xml,内容类似于:

<ehcache>    <diskStore path="F:/temp/ehcahe"/>    <defaultCache        maxElementsInMemory="10000"        eternal="false"        timeToIdleSeconds="120"        timeToLiveSeconds="120"        overflowToDisk="true"        />    <cache name="sampleCache1"        maxElementsInMemory="10000"        eternal="false"        timeToIdleSeconds="300"        timeToLiveSeconds="600"        overflowToDisk="true"        /> </ehcache>

3.在Hibernate.cfg.xml中对需要加入二级缓存的类进行如下配置:

<class-cache usage="read-only" class="com.hurricane.domain.Teacher"/>



查询缓存的使用:

1.在Hibernate.cfg.xml中开启查询缓存:

<property name="hibernate.cache.use_query_cache">true</property>
2.在调用Query的list方法前设置cacheable为true,如下:

Query query = session.createQuery("from Teacher where tid<10");query.setCacheable(true);List list = query.list();


注:二级缓存算法:LRU,LFU,FIFO

ehcache.xml中配置项详解见http://blog.163.com/zsq303288862@126/blog/static/937459612011116112640694/

参考:http://blog.csdn.net/l271640625/article/details/20528573

http://blog.csdn.net/jrn1012/article/details/39481975

http://ligf06.iteye.com/blog/1711137




原创粉丝点击