Hibernate + ehcache配置使用

来源:互联网 发布:vscode设置字体颜色 编辑:程序博客网 时间:2024/06/05 18:39

1:下载EhCache.jar

2:在Spring配置文件中applicationContext.xml中 添加

 

 <!-- Hibernate二级缓存 -->

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource" ref="dataSource"/>
  <property name="hibernateProperties">
   <props>
        <prop key="hibernate.cache.provider_class"> net.sf.ehcache.hibernate.EhCacheProvider</prop><!-- 指定cache实现类 -->  
        <prop key="cache.use_second_level_cache">true</prop><!-- 启用二级缓存 --> 
        <prop key="hibernate.cache.use_query_cache">true</prop><!-- 启用查询缓存 --> 
        <prop key="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</prop>

  </props>  

</property>

</bean>

或者在相关的hibernate配置文件中添加上面红色部分

 

3:配置ehcache.xml文件

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

<ehcache>
 <!-- 
  maxElementsInMemory="10000"  中最多允许保存的数据对象的数量
  external=“false” //缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期
  timeToIdleSeconds=“1000”  //缓存数据钝化时间(设置对象在它过期之前的空闲时间) 
  timeToLiveSeconds=“1000”  //缓存数据的生存时间(设置对象在它过期之前的生存时间)
  overflowToDisk=“false” />    //内存不足时,是否启用磁盘缓存 
  memoryStoreEvictionPolicy="LRU" //内存不足时数据对象的清除策略
 -->
 <defaultCache
  maxElementsInMemory="10000"
  eternal="false"
  timeToIdleSeconds="1000"
  timeToLiveSeconds="1000"
  overflowToDisk="false"
  memoryStoreEvictionPolicy="LRU"
 />
</ehcache>

 

4:在需要缓存的实体类中添加如下红色代码

@Entity
@Table
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Student extends BaseModel {}

红色部分表示读和写都写入缓存,可以根据自己的需要选择策略

 

0 0
原创粉丝点击