首页 > 解决方案 > 如何使用结果对象的 id 来使用 Cacheable?

问题描述

public class MyClass{
    @Id
    @Column(name = "id", nullable = false)
    Long id;

    private AnotherClass anotherClass;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "another_id")
    @Cacheable(value = "getAnotherClass", unless = "#result == null", key = "#id")
    public AnotherClass getAnotherClass(){
        return anotherClass;
    }
}

public class AnotherClass{
    @Id
    @Column(name = "id", nullable = false)
    Long id;
}

有2个班。MyClass包含 的外键AnotherClass

我需要以使用ofgetAnotherClass缓存的方式缓存。idAnotherClass

怎么做?

标签: javaehcachespring-cache

解决方案


  1. Spring @Cacheable 不能在没有方法参数的情况下使用。第一次调用带有@Cacheable 注释的方法时,它会被执行,并且它的返回值使用键[作为方法参数传递的实例的参数] 存储在缓存中。下次,如果使用相同的键[例如相同的参数]调用该方法,则直接从Cache返回结果,而不执行该方法。

  2. 您正在尝试将 ORM(hibernate) 与 spring 缓存混合,这似乎是一个坏主意,相反,您可以利用hibernate 提供的二级缓存参考https://www.journaldev.com/2980/hibernate-ehcache-hibernate -二级缓存

  3. 如果你还想使用spring cacheable,写一个服务来实现spring缓存。有条件检查缓存存储库中的对象是否可用,否则使用 ORM 获取引用( https://www.foreach.be/blog/spring-cache-annotations-some中的“组合 @CachePut 和 @Cacheable 以优化缓存使用”部分- 技巧 - 技巧


推荐阅读