java - 为什么我们必须在 Hibernate 中使用 @Cacheable 以及 @Cache 来进行二级缓存?
问题描述
我想知道为什么我们必须使用2个注解才能使用Hibernate中的二级缓存。
我们声明:
@Cacheable
@Cache
为什么我们不直接@Cache
用选项声明呢?
解决方案
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();
推荐阅读
- networking - 自己做了个DNS服务器,怎么给主机添加照片?
- node.js - 使用 gcloud app deploy 推送 docker 镜像失败
- fiddler - FiddlerScript 使用 oSession.SaveResponse 保存空白文件
- php - 将 json 对象数据传递给 php 文件
- python - 如何将来自 TensorFlow (v. 2) Hub 的预训练 KerasLayer 和 tfrecords 结合起来?
- java - 在游戏中获得经验的实现
- bash - 将每 2 行保存到一个文件中
- c# - WPF FlowDocument 确定块将在哪个页面上
- html - 如何放置像以前一样旋转 90 度以适合 div 容器和其他图像的图像?
- lambda - 怎样才能找到对应的列表?