首页 > 解决方案 > 为什么我们必须在 Hibernate 中使用 @Cacheable 以及 @Cache 来进行二级缓存?

问题描述

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

我们声明:

@Cacheable
@Cache

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

标签: javahibernatejpacachingehcache

解决方案


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

You don't need to use both, but you can.
@Cache is the Hibernate cache interface.
@Cacheable is the JPA cache interface.
@Cacheable will only work if the caching element(persistence.xml) is set to ENABLE_SELECTIVE or DISABLE_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).

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

That's exactly what you should do. A basic configuration of second level cache(I am using 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
Note 2: Collections are not cached by default, you need to explicitly mark them with @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();

推荐阅读