以下配置基于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);