Spring Boot + Hibernate基于JpaRepository的查询缓存

以下配置基于spring boot版本1.4.2.RELEASE,默认引入的hibernate版本为5.0.11.Final,ehcache版本2.10.3。
Ehcache作为Hibernate的二级缓存的实现。

1.application.properties中,添加:

#打开hibernate统计信息
spring.jpa.properties.hibernate.generate_statistics = true

#打开二级缓存
spring.jpa.properties.hibernate.cache.use_second_level_cache = true

#打开查询缓存
spring.jpa.properties.hibernate.cache.use_query_cache = true

#指定缓存provider
spring.jpa.properties.hibernate.cache.region.factory_class = org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory

#配置shared-cache-mode
spring.jpa.properties.javax.persistence.sharedCache.mode = ENABLE_SELECTIVE

2.接口方法加上@QueryHints注解

@Query("from UserAddress where receiveAddress like %:receiveAddress%")
@QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value ="true") })  // 使用查询缓存
public List<UserAddress> findList(@Param("receiveAddress") String receiveAddress);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容