简体   繁体   English

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

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

I want to know why we have to use 2 annotations to use the second-level of cache in Hibernate.我想知道为什么我们必须使用2个注解才能使用Hibernate中的二级缓存。

We declare:我们声明:

@Cacheable
@Cache

Why don't we declare directly @Cache with the options?为什么我们不直接用选项声明@Cache?

Thank you谢谢

I want to know why we have to use 2 annotations to use the second-level of cache in Hibernate.我想知道为什么我们必须使用2个注解才能使用Hibernate中的二级缓存。

You don't need to use both, but you can.您不需要同时使用两者,但可以。
@Cache is the Hibernate cache interface. @Cache是 Hibernate 缓存接口。
@Cacheable is the JPA cache interface. @Cacheable是 JPA 缓存接口。
@Cacheable will only work if the caching element( persistence.xml ) is set to ENABLE_SELECTIVE or DISABLE_SELECTIVE . @Cacheable只有在缓存元素( persistence.xml )设置为ENABLE_SELECTIVEDISABLE_SELECTIVE时才有效。

As per this : Some developers consider that it is a good convention to add the standard @javax.persistence.Cacheable annotation as well ( although not required by Hibernate ).按照这个:一些开发人员认为添加标准 @javax.persistence.Cacheable 注释也是一个很好的约定(尽管 Hibernate 不需要)。

Why don't we declare directly @Cache with the options?为什么我们不直接用选项声明@Cache?

That's exactly what you should do.这正是你应该做的。 A basic configuration of second level cache(I am using Spring Boot):二级缓存的基本配置(我使用的是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 {

Note 1 : The above is using Ehcache 2.x注1 :以上是使用Ehcache 2.x
Note 2 : Collections are not cached by default, you need to explicitly mark them with @Cache .注意 2 : Collections 默认不缓存,您需要使用@Cache显式标记它们。


BONUS:奖金:
If you want to check the statistics:如果要查看统计信息:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM