hibernate二级缓存配置

来源:互联网 发布:什么叫手机网络病毒 编辑:程序博客网 时间:2024/05/20 00:52

小说明一哈:我们从数据库查询出来,需要有session工厂,session,拿到连接,执行,关闭连接等等,但是如此反复,是很耗费资源的,那么hibernate中存在的机制是现在一级缓存中找,也就是session,如果没有到二级缓存,也就是sessionFactory,在没有再去数据库中查找,那么如此就体现出一个二级缓存的重要性,需要注意的,这些都是在内存中的东西,如果内存清空,任你是大罗金仙,也无能为力!
那么,上配置:
现在[model]-hbm.xml中加权限配置(读写操作的设定):

<cache usage="read-write"/>

这是在class里面的
接着是application的可选配置配置(在ssh框架中),如果是单用hibernate框架,那么在hibernate.cfg.xml的可选配置中设置这些:

<!--开启二级缓存-->hibernate.cache.use_second_level_cache=true             hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory   <!--详细的配合信息在/ehcache.xml中-->            net.sf.ehcache.configurationReourceName=/ehcache.xml<!--在查询中使用二级缓存-->hibernate.cache.use_query_cache=truehibernate.generate_statistics=false

在/ehache.xml中的配置:

<?xml version="1.0" encoding="UTF-8"?><ehcache>    <!-- 如果缓存中的对象存储超过指定的缓存数量的对象存储的磁盘地址 -->    <diskStore path="D://ehcache"></diskStore>    <!--         默认cache:如果没有对应的特定区域的缓存,就是用默认缓存        name:cache 唯一标识        eternal:缓存是否永久有效        maxElementsInMemory:内存中最大缓存对象数        overflowToDisk(true,false):缓存对象达到最大数后,将缓存写到硬盘中        diskPersistent:硬盘持久化        timeToIdleSeconds:缓存清除时间        timeToLiveSeconds:缓存存活时间        memoryStoreEvictionPolicy:缓存清空策略        1FIFO:first in first out先进先出        2LFU:less Frequently Used 一直以来最少被使用的        3LRU:least Recently Used 最近最少使用的     -->    <defaultCache         maxElementsInMemory="10000"        eternal="false"        timeToIdleSeconds="300"        timeToLiveSeconds="600"        overflowToDisk="true"    /></ehcache>

这里有详细的说明,嘎嘎!
另外,在查询的方法中需加入:

Query query = currentSession().createQuery(hql);//这就是说明使用了二级缓存query.setCacheable(true);

好了,完事!

0 0