您的位置:首页 > 编程语言 > Java开发

Spring环境下Hibernate二级缓存的应用

2013-05-16 21:56 459 查看
在数据不经常变化的地方,为了能够提高网站系统的执行效率,使用缓存是我们经常想到的解决方式。Hibernate的缓存分为三类,我们在平时应用开发中,最容易忽略的就是它的一级缓存,因为它的生命周期与session一致。二级缓存的应用是最普遍的,也是行之有效的。那么怎么配置它呢?主要分为以下几步:

《1》搭建Spring+Hibernate环境

《2》加载Hibernate-ehcache相应的jar包

《3》在applicationContext.xml中添加缓存的相关配置:

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<property name="dataSource" ref="dataSource" ></property>

<property name="mappingDirectoryLocations">

<list>

<value>classpath:com/entity/test</value>

</list>

</property>

<property name="hibernateProperties">

<props>

<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>

<prop key="hibernate.show_sql">false</prop>

<!-- 开启hibernate的查询缓存 -->

<prop key="hibernate.cache.use_query_cache">true</prop>

<!-- 开启hibernate二级缓存-->

<prop key="hibernate.cache.use_second_level_cache">true</prop>

<!-- hibernate缓存管理类-->

<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>

<!-- hibernate缓存配置文件-->

<prop key="hibernate.cache.configurationResourceName">ehcache.xml</prop>

</props>

</property>

</bean>

《4》在src目录下创建ehcache.xml缓存文件,内容大致如下:

<?xml version="1.0" encoding="UTF-8"?>

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false">

<diskStore path="java.io.tmpdir" />

<defaultCache eternal="false"

maxElementsInMemory="1000"

overflowToDisk="false"

diskPersistent="false"

timeToIdleSeconds="0"

timeToLiveSeconds="600"

memoryStoreEvictionPolicy="LRU" />

<cache name="departCache"

eternal="false"

maxElementsInMemory="100"

overflowToDisk="false"

diskPersistent="false"

timeToIdleSeconds="0"

timeToLiveSeconds="300"

memoryStoreEvictionPolicy="LRU" />

</ehcache>

其中具体的含义可以参考网上的定义,这里不再标注。

《5》在dao中引入二级缓存:

HibernateTemplate template = this.getHibernateTemplate();

template.setCacheQueries(true);//开启hibernate二级缓存

List result = template.find(sql);

template.setCacheQueries(false);

总结:初次查询会连接数据库,其后会从缓存中返回结果,而不会继续从数据库中读取。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: