gpt4 book ai didi

java - 如何在不使用查询缓存的情况下缓存 Spring Data JPA 查询方法的结果?

转载 作者:IT老高 更新时间:2023-10-28 21:03:35 27 4
gpt4 key购买 nike

我有一个带有 Spring Data JPA( hibernate 后端)存储库类的 Spring Boot 应用程序。我添加了几个自定义查找器方法,其中一些带有特定的 @Query 注释来告诉它如何获取数据。我已经为 hibernate 二级缓存设置了 EhCache,但到目前为止,我可以获得这些结果缓存的唯一方法是启用 hibernate 查询缓存。我更愿意定义一个特定的缓存并将实际的域对象存储在那里,就像它是一个普通的查找器一样。以下是我的 repo 代码:

public interface PromotionServiceXrefRepository extends PagingAndSortingRepository<PromotionServiceXref, Integer> {

@Query("SELECT psx FROM Customer c " +
"JOIN c.customerProductPromotions cpp " +
"JOIN cpp.productPromotion pp " +
"JOIN pp.promotion p JOIN p.promotionServiceXrefs psx " +
"WHERE c.customerId = ?1")
@QueryHints(@QueryHint(name = "org.hibernate.cacheable", value = "true"))
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY, region = "promotionServiceXrefByCustomerId")
Set<PromotionServiceXref> findByCustomerId(int customerId);
}

这是我定义的“promotionServiceXrefByCustomerId”缓存,没有被使用:

<cache name="promotionServiceXrefByCustomerId" overflowToDisk="true" diskPersistent="true"
maxEntriesLocalHeap="3000000" eternal="true" diskSpoolBufferSizeMB="20" memoryStoreEvictionPolicy="LFU"
transactionalMode="off" statistics="true">
</cache>

我做错了什么?如果我启用 StandardQueryCache 那么这些数据会被缓存在那里并且 hibernate 不会执行查询。但是当我禁用查询缓存时,它不会被缓存。我在这里做错了什么?请帮忙!

最佳答案

您的代码不起作用的原因是 @Cache 不打算以这种方式工作。如果要缓存一个查询方法执行的结果,最简单的方法是使用Spring的caching abstraction .

interface PromotionServiceXrefRepository extends PagingAndSortingRepository<PromotionServiceXref, Integer> {

@Query("…")
@Cacheable("servicesByCustomerId")
Set<PromotionServiceXref> findByCustomerId(int customerId);

@Override
@CacheEvict(value = "servicesByCustomerId", key = "#p0.customer.id")
<S extends PromotionServiceXref> S save(S service);
}

此设置将导致调用 findByCustomerId(…) 的结果由客户标识符缓存。请注意,我们在重写的 save(…) 方法中添加了 @CacheEvict,这样每当保存实体时,我们使用查询方法填充的缓存就会被清除。这可能也必须传播到 delete(…) 方法。

现在您可以继续配置一个专用的 CacheManager(请参阅 reference documentation 了解详细信息)以插入您喜欢的任何缓存解决方案(在此处使用纯 ConcurrentHashMap )。

 @Configuration
@EnableCaching
class CachingConfig {

@Bean
CacheManager cacheManager() {

SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.addCaches(Arrays.asList(new ConcurrentMapCache("servicesByCustomerId)));

return cacheManager;
}
}

关于java - 如何在不使用查询缓存的情况下缓存 Spring Data JPA 查询方法的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26242492/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com