最近用SSH帮老师做个项目,涉及到一些表的查询,而这些表的字段相对较多,每次查询都是执行SQL语句访问数据库,这样子就导致每次查询的速度很慢。所以我想到了用hibernate的二级缓存机制,至于hibernate二级缓存详细的原理可以百度找博客了解,这里就不多累赘。
spring整合hibernate配置二级缓存步骤:
1.配置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">
<!-- DISKStury路径必须配置,不然报错 -->
<diskStore path="D:\\mytemp"/>
<!-- 数据过期策略 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="600"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
<!-- 具体到某个类的数据过期策略 -->
<!-- <cache name="com.lanhuigu.hibernate.entity.Customer"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/> -->
</ehcache>
2.在spring中整合hibernate二级缓存
2.1<!-- 配置SessionFactory创建 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"><!-- 指定hibernate核心配置文件 -->
<property name="configLocations" value="classpath:hibernate.cfg.xml"></property>
<property name="hibernateProperties">
<props>
<!-- 是否开启二级缓存 -->
<prop key=" hibernate.cache.use_second_level_cache">true</prop>
<!-- 是否启用查询缓存 -->
<prop key=" hibernate.cache.use_query_cache">true</prop>
<!-- 配置二级缓存提供商 -->
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<!-- 配置 ehcache.xml的路径-->
<prop key="hibernate.net.sf.ehcache.configurationResourceName">classpath:ehcache.xml</prop>
</props>
</property>
</bean>
2.2为hibernateTemplate打开缓存查询
<!-- 配置HibernateTemplate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<!-- 注入sessionFactory -->
<property name="sessionFactory" ref="sessionFactory"></property>
<property name="cacheQueries" value="true"/>
</bean>
3.指定哪些实体类加入缓存
只需在实体类映射的hbm.xml文件中加入: <cache usage="read-write"/><!-- 配置缓存策略 -->