java - 如何使用结果对象的 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
缓存的方式缓存。id
AnotherClass
怎么做?
解决方案
Spring @Cacheable 不能在没有方法参数的情况下使用。第一次调用带有@Cacheable 注释的方法时,它会被执行,并且它的返回值使用键[作为方法参数传递的实例的参数] 存储在缓存中。下次,如果使用相同的键[例如相同的参数]调用该方法,则直接从Cache返回结果,而不执行该方法。
您正在尝试将 ORM(hibernate) 与 spring 缓存混合,这似乎是一个坏主意,相反,您可以利用hibernate 提供的二级缓存参考https://www.journaldev.com/2980/hibernate-ehcache-hibernate -二级缓存
如果你还想使用spring cacheable,写一个服务来实现spring缓存。有条件检查缓存存储库中的对象是否可用,否则使用 ORM 获取引用( https://www.foreach.be/blog/spring-cache-annotations-some中的“组合 @CachePut 和 @Cacheable 以优化缓存使用”部分- 技巧 - 技巧)
推荐阅读
- sql-server - Microsoft Access 到 SQL Server 转换 - 插入时无效使用 null
- excel - 仅当其他两列不是空白excel时如何计算相同值的数量
- c++ - 如何在 DirectX 中将图像裁剪成圆形
- android - 双向绑定:如何在 EditText 上格式化货币 TextWatcher?
- python - Fallback to normal function if celery is not active
- matlab - avoiding a for loop to convert date/time string to number
- amazon-web-services - How to change termination protection by boto3
- visual-studio-code - VS Code 终端上的透明光标
- javascript - javascript文件中的错误,而没有错误
- ios - Conditional map function in Swift