[英]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_SELECTIVE
或DISABLE_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.