为什么我们必须使用@Cacheable 以及Hibernate 中的@Cache 作为二级缓存?

Why do we have to use @Cacheable as well as @Cache in Hibernate for second-level of cache?

想知道在Hibernate中为什么要使用2个注解才能使用二级缓存

我们声明:

@Cacheable
@Cache

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

I want to know why we have to use 2 annotations to use the second-level of cache in Hibernate.

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

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

Why don't we declare directly @Cache with the options ?

这正是您应该做的。二级缓存基本配置(我用的是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:集合默认不缓存,需要用@Cache显式标记。


奖金:
如果要查看统计数据:

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

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