一、pom.xml
<!-- ehcache缓存 --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.6.9</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>${hibernate.version}</version> </dependency>
二、ehcache.xml
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <!-- maxElementsInMemory:缓存中最大允许创建的对象数 eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期 timeToIdleSeconds:缓存数据钝化时间(设置对象在它过期之前的空闲时间) timeToLiveSeconds:缓存数据的生存时间(设置对象在它过期之前的生存时间) overflowToDisk:内存不足时,是否启用磁盘缓存 clearOnFlush:内存数量最大时是否清除 --> <defaultCache maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="1200" timeToLiveSeconds="1200" overflowToDisk="false" clearOnFlush="true"> </defaultCache> <!-- 单独对某个entity的缓存策略设置--> <!-- <cache name="com.mushi.core.entity.user.User" maxElementsInMemory="100" eternal="false" timeToIdleSeconds="1200" timeToLiveSeconds="1200" overflowToDisk="false" clearOnFlush="true"> </cache> --> </ehcache>
三、applicationContext.xml
<!-- Jpa Entity Manager 配置 --> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 设置hibernate方言 可以使用java类动态生成 --> <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" /> <property name="packagesToScan" value="com.mushi.core" /> <property name="jpaProperties"> <props> <!-- 命名规则 My_NAME->MyName --> <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop> <!-- 配置hibernate的属性 如果使用log4jdbc这个就不起作用 --> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">false</prop> <!-- <prop key="hibernate.hbm2ddl.auto">create</prop> -->
<!-- 开启二级缓存 和 查询缓存(使用jpa时必须开启) 默认ehcache.xml配置路径为根目录 classpath:下 -->
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop> <prop key="hibernate.cache.use_second_level_cache">true</prop> <prop key="hibernate.cache.use_query_cache">true</prop> </props> </property> </bean>
四、在dao中添加注解
@Query("select user from User user ORDER BY user.createtime DESC") @QueryHints({@QueryHint(name = "org.hibernate.cacheable", value ="true") }) List<User> getAll();
使用@QueryHints注解 令查询方法使用查询缓存
五、在类中定义
@Entity @Table(name = "DAE_USER") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class User extends ObjectEntity{ }
外:默认情况下二级缓存只会对load get 之类的方法缓存, 想list iterator 之类的方法也使用缓存 必须跟查询缓存一起使用, 重写查询方法 例如:
return (User) getCurrentSession().createQuery(hql).setCacheable(true).uniqueResult();