1

我只是尝试将项目的结果存储在缓存中,除了密钥之外一切顺利。

SimpleKeyGenerator 通常根据参数保存对象或结果,在我的情况下,我想将对象存储在缓存中,键应该是列表中对象的属性,这是一个示例。

 public class Item{
    private Long id;
    private Long reference;
    private Integer status;
    //setter and getter
 }

 public interface ItemRepository extends JpaRepository<Long,Item>{

   @Cachable("items")
   List<Item> findByReferenceAndStatus(Long reference, Integer status);
 }

现在我想根据 item.id 将每个对象存储在缓存中,我知道我们可以使用注释的 key 属性,但是如何使用 SpEL 访问每个项目的 Id。不幸的是,创建自定义密钥生成器无济于事,因为所有这些都基于参数、目标类和方法。

有什么建议吗?

4

1 回答 1

0

我相信您想优化缓存存储以便稍后按项目ID查询。

如果您为您的实体正确配置了 JPA 二级,则您不需要这样做,当它配置良好时,使用 JPA 按 ID 加载实体将自动使用二级。

要获得单一结果,只需在关键属性上使用 Cache SpEL #result:

https://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html#cache-spel-context-tbl

@Cacheable(cacheNames="item", key="#result.id")
于 2017-02-22T17:36:46.700 回答