繁体   English   中英

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

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

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

我们声明:

@Cacheable
@Cache

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

谢谢

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

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

按照这个:一些开发人员认为添加标准 @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 : Collections 默认不缓存,您需要使用@Cache显式标记它们。


奖金:
如果要查看统计信息:

//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