spring-data-jpa是否具有L2缓存实现?

Max*_* Wu 1 java caching spring-data-jpa

我正在尝试以最少的设置创建具有L2缓存的存储库。我的数据库是postgresql。

我从使用maven的spring-boot-sample-data-jpa-archetype项目开始。我删除了HSQL并创建了一个DataSource bean来连接到postgresql。还可以使用ddl创建架构并导入初始脚本数据。

我还已将@Cacheable添加到我的实体中。然后,我使用单元测试使用存储库查询实体10次。花费了1〜49ms。这给我留下了两个问题。

  1. 存储库是否从L1缓存中受益?我怎么知道我要访问缓存或数据源?
  2. 如何启用二级缓存?Spring数据有自己的实现吗?

Max*_* Wu 5

经过一些测试和@dunni的帮助。我会回答我自己的问题。Spring使用Hibernate作为JPA的实现。Spring数据为休眠提供了一些包装。还需要选择和执行缓存。

要启用L2缓存,请将这些属性添加到您的项目中。

  1. spring.jpa.properties.hibernate.cache.use_second_level_cache = true
  2. spring.jpa.properties.hibernate.cache.use_query_cache = true
  3. spring.jpa.properties.hibernate.cache.region.factory_class = org.hibernate.cache.ehcacne.EhCacheRegionFactory

和依赖项hibernate-ehcache

然后,将@Cacheable(true)添加到您的实体模型类。扩展存储库接口,spring将使用命名约定生成实现。例如

@QueryHints({@QueryHint(name="org.hibernate.cacheable", value="true")})
Entity findByName(String name)
Run Code Online (Sandbox Code Playgroud)

您也可以实现该接口。但这需要向您的查询对象添加提示以激活L2缓存。

query.setHint("org.hibernate.cacheable", true);
Run Code Online (Sandbox Code Playgroud)

要验证缓存是否正常工作,可以使用以下属性查看SQL是否已执行。

  1. spring.jpa.show-sql = true
  2. spring.jpa.properties.hibernate.format_sql = true