【问题标题】:How to use Cacheable using the result Object's id?如何使用结果对象的 id 来使用 Cacheable?
【发布时间】:2019-01-02 06:50:01
【问题描述】:
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 的外键。

我需要使用AnotherClassid 缓存getAnotherClass

怎么做?

【问题讨论】:

  • spring.io/guides/gs/caching这个方法你试过吗?
  • 使用@Cacheable(value = "getAnotherClass") 仍然会导致大量实际的数据库调用。

标签: java ehcache spring-cache


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

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

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

【讨论】:

    猜你喜欢
    • 2012-09-18
    • 2020-06-07
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 2018-11-09
    • 1970-01-01
    相关资源
    最近更新 更多