在applicationContext.xml文件中添加以下代碼:
<prop key= "hibernate.cache.use_second_level_cache" > true </prop>
<!--設置緩存機制爲二級緩存 --> <prop key= "hibernate.cache.use_query_cache" > true </prop>
<!--啓動查詢緩存 --> <prop key= "hibernate.cache.provider_class" >org.hibernate.cache.EhCacheProvider</prop> <!--設置二級緩存的Provider類 --> <prop key= "hibernate.cache.provider_configuration_file_resource_path" >WEB-INF/classes/ehcache.xml</prop> <!--設置緩存的配置文件路徑 --> |
將ehcache.xml文件放到src下面,並配置ehcache.xml文件如下:
<ehcache> <diskStore path="D:\cache" /> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" overflowToDisk="true" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" /> <cache name="net.nk.entity.DataAttr" maxElementsInMemory="800" eternal="false" overflowToDisk="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" /> <cache name="net.nk.entity.SmContentCategory" maxElementsInMemory="800" eternal="false" overflowToDisk="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" /> <cache name="net.nk.entity.SmProduct" maxElementsInMemory="800" eternal="false" overflowToDisk="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" /> <cache name="net.nk.entity.SmDepartment" maxElementsInMemory="800" eternal="false" overflowToDisk="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" /> <cache name="net.nk.entity.SmUser" maxElementsInMemory="800" eternal="false" overflowToDisk="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" /> <cache name="net.nk.entity.DataAttrValue" maxElementsInMemory="3000" eternal="false" overflowToDisk="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" /> <cache name="net.nk.entity.DataAm" maxElementsInMemory="800" eternal="false" overflowToDisk="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" /> <cache name="net.nk.entity.DataAttrGroup" maxElementsInMemory="400" eternal="false" overflowToDisk="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" /> </ehcache>
在設置了緩存機制的類的xml文件中添加一段代碼<cache usage="read-write" region="net.nk.entity.SmProduct"代碼如下:
<hibernate-mapping> <!--SM_PRODUCT表的hibernate映射描述文件 --> <class name="net.nk.entity.SmProduct" table="SM_PRODUCT" > <cache usage="read-write" region="net.nk.entity.SmProduct"/> <!-- ID --> <id name="id" type="string"> <column name="ID" /> <generator class="assigned" /> </id>
其中類的xml文件中的region設置要和ehcache.xml文件中的保持一致,此處是通過包名+類名的方式。
在調用數據庫數據方法時,可採取以下設置:
protected List<POJO> getAll(Class<T> entityClass,boolean iscache) throws SSHException { HibernateTemplate ht = getHibernateTemplate(); if(iscache){ ht.setCacheQueries(true); } return ht.find("from "+entityClass.getName());//getHibernateTemplate().loadAll(entityClass); }
至此,可以通過放開hibernate的show_sql來查看是否緩存機制生效了
原文地址:http://www.cnblogs.com/xiangpiaopiao2011/archive/2011/12/15/2289222.html