【问题标题】:Why do we have to use @Cacheable as well as @Cache in Hibernate for second-level of cache?为什么我们必须在 Hibernate 中使用 @Cacheable 以及 @Cache 来进行二级缓存?
【发布时间】:2021-03-08 16:13:33
【问题描述】:

我想知道为什么我们必须使用2个注解才能使用Hibernate中的二级缓存。

我们声明:

@Cacheable
@Cache

我们为什么不直接用选项声明@Cache?

【问题讨论】:

  • 我相信 @Cacheable 是一个 Spring 注解,用于缓存任何数据集,无论是否来自数据库。
  • 你能提供更多的上下文吗?哪个文档/示例告诉您必须同时使用这两个注释?您能否还提供一个最小的代码示例而不仅仅是两个注释?您使用的是哪个版本的 Hibernate 和 JPA?

标签: java hibernate jpa caching ehcache


【解决方案1】:

我想知道为什么我们必须使用 2 个注解来使用 Hibernate 中的二级缓存。

您不需要同时使用两者,但可以。
@Cache 是 Hibernate 缓存接口。
@Cacheable 是 JPA 缓存接口。
@Cacheable 仅在以下情况下才有效缓存元素 (persistence.xml) 设置为 ENABLE_SELECTIVE 或 DISABLE_SELECTIVE。

根据this: 一些开发人员认为添加 标准的@javax.persistence.Cacheable 注解(虽然不是 Hibernate 需要)。

我们为什么不直接用选项声明@Cache?

这正是你应该做的。二级缓存的基本配置(我用的是Spring Boot):

//In build.gradle:
implementation 'org.hibernate:hibernate-ehcache' //If you are specifying a version, make sure that it is the same version as your Hibernate version you are using.

//Hibernate properties(can also be externalized to application.properties):
properties.put("hibernate.cache.use_second_level_cache", "true"); //hibernate.cache.use_second_level will also work
properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");

//In the entity class:
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class MyClass implements Serializable {

注意1:以上使用的是Ehcache 2.x
注意2:集合默认不缓存,需要显式标记@987654329 @.


奖励:
如果您想查看统计信息:

//Add this property:
properties.put("hibernate.generate_statistics", "true");

//And somewhere in your code:
sessionFactory.getStatistics();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-19
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    • 2011-10-19
    • 2010-09-25
    • 1970-01-01
    相关资源
    最近更新 更多