一、了解
Hibernate的session提供了一级缓存,每个session,对同一个id进行两次load,不会发送两条sql给数据库,但session关闭时,一级缓存失效。
二级缓存是SessionFactory级别的全局缓存,它底下可以使用不同的缓存类库,比如ehcache、oscache等
对缓存若想进步了解可参考以下网址http://www.360doc.com/content/10/0917/17/2560742_54412898.shtml
二、配置
1、在applicationContext.xml中定义如下:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop> <prop key="hibernate.cache.use_query_cache">true</prop> <prop key="hibernate.cache.use_second_level_cache">true</prop> <prop key="hibernate.cache.configurationResourceNam e">ehcache.xml</prop> </props> </property> <property name="mappingResources"> <list> <value>com/crm/model/User.hbm.xml</value> </list> </property> </bean>
2、在src目录下创建ehcache.xml,配置信息如下:
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="180" overflowToDisk="true" diskPersistent="false" diskExpiryThreadInterval Seconds="120" memoryStoreEvictionPolic y="LRU" /> <!-- 查询缓存 --> <cache name="org.hibernate.cache.StandardQueryCache" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="4200" overflowToDisk="true"> </cache> <!-- 二级缓存 --> <cache name="org.hibernate.cache.UpdateTimestampsCache" maxElementsInMemory="5000" eternal="true" timeToIdleSeconds="0" timeToLiveSeconds="0" overflowToDisk="false" /> <!-- 给Model设置缓存 --> <cache name="com.crm.model.User" maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="100" timeToLiveSeconds="4200" overflowToDisk="true" /> </ehcache>
maxElementsInMemory属性用于指定缓存中最多可放多少个对象。 eternal属性指定缓存是否永久有效。 timeToIdleSeconds属性指定缓存多久未被使用便清理掉。 timeToLiveSeconds属性指定缓存的生命长度。 diskPersistent属性指定缓存是否被持久化到硬盘中,保存路径由标签指定。
3、在User.hbm.xml里加上<cache usage="read-write" />,如下图所示
注意:
启动Tomcat,如发现如下错误
Could not find configuration [org.hibernate.cache.UpdateTimestampsCache]; using defaults. Could not find configuration [org.hibernate.cache.StandardQueryCache]; using defaults.
则是第二步没有做,加上即可.配置完毕
4、执行查询缓存时,若使用Criteria需设置如下(示例):
public List getUserInfoByCondition(Page page) { List users = null; Criteria criteria = this.getSession().createCriteria(User.class); criteria.setFirstResult(page.getBeginIndex()); criteria.setMaxResults(page.getEveryPage()); criteria.setCacheable(true); users = criteria.list(); return users; } 至此配置过程完毕。