总结一切(L2 缓存和查询缓存):
首先要做的是将缓存提供程序(我推荐使用 EhCache)添加到您的类路径中。
休眠
添加hibernate-ehcache 依赖项。该库包含现已停产的 EhCache 2。
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>your_hibernate_version</version>
</dependency>
休眠>=5.3
在较新版本的 Hibernate 缓存中实现了 JSR-107 (JCache) API。所以需要 2 个依赖项 - 一个用于 JSR-107 API,第二个用于实际的 JCache 实现(EhCache 3)。
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jcache</artifactId>
<version>your_hibernate_version</version>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.6.3</version>
<scope>runtime</scope>
</dependency>
现在让我们转到 application.properties/yml 文件:
spring:
jpa:
#optional - show SQL statements in console.
show-sql: true
properties:
javax:
persistence:
sharedCache:
#required - enable selective caching mode - only entities with @Cacheable annotation will use L2 cache.
mode: ENABLE_SELECTIVE
hibernate:
#optional - enable SQL statements formatting.
format_sql: true
#optional - generate statistics to check if L2/query cache is actually being used.
generate_statistics: true
cache:
#required - turn on L2 cache.
use_second_level_cache: true
#optional - turn on query cache.
use_query_cache: true
region:
#required - classpath to cache region factory.
factory_class: org.hibernate.cache.ehcache.EhCacheRegionFactory
对于 EhCache 3(或 Hibernate >=5.3),应该使用这个区域工厂:
factory_class: org.hibernate.cache.jcache.JCacheRegionFactory
您还可以为 Hibernate 启用 TRACE 级别日志记录以验证您的代码和配置:
logging:
level:
org:
hibernate:
type: trace
现在让我们继续看代码。要在您的实体上启用 L2 缓存,您需要添加这两个注释:
@javax.persistence.Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) //Provide cache strategy.
public class MyEntity {
...
}
注意 - 如果您想缓存 @OneToMany 或 @ManyToOne 关系 - 在此字段上添加 @Cache 注释。
要在 spring-data-jpa 存储库中启用查询缓存,您需要添加正确的 QueryHint。
public class MyEntityRepository implements JpaRepository<MyEntity, Long> {
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
List<MyEntity> findBySomething(String something);
}
现在通过日志验证您的查询是否只执行一次,并记得关闭所有调试内容 - 现在您已完成。
注意 2 - 如果您想保持默认值而不在日志中收到警告,您也可以将 missing cache strategy 定义为 create:
spring:
jpa:
properties:
hibernate:
javax:
cache:
missing_cache_strategy: create