java - Hibernate 二级缓存似乎不起作用

标签 java hibernate orm caching second-level-cache

我目前正在尝试使用 hibernate 附带的缓存提供程序让 hibernate 工作。

net.sf.ehcache.hibernate.SingletonEhCacheProvider

我在我的 hibernate.cfg.xml 文件中引用的 ecache.xml 中启用了默认缓存和类特定缓存。类/映射文件特定缓存被定义为处理多达 20000 个对象。

但是,自从我在我用来测试它的映射文件之一上打开缓存映射后,我没有看到任何性能提升。

我的测试如下。

加载特定映射文件 im 测试的 10000 个对象(这应该会影响数据库并成为瓶颈)。 接下来我去加载相同的 10000 个对象,因为此时我希望缓存被命中并看到显着的性能提升。已尝试在我测试的 hibernate 映射 xml 文件上同时使用“只读”和“读写”缓存映射。

我想知道他们是否需要做任何事情来确保在加载对象时先于数据库命中缓存?

请注意,作为测试的一部分,使用类似于下面的内容(一次分页 1000 条记录)通过这 10000 条记录分页。

Criteria crit = HibernateUtil.getSession() .createCriteria( persistentClass );
       crit.setFirstResult(startIndex);
       crit.setFetchSize(fetchSize);
       return crit.list();

已经看到 criteria 有一个缓存模式 setter (setCacheMode() ) 那么我应该用它做什么吗?

我注意到使用下面的统计代码,内存中有 10000 个对象(以及我想象的 hiberante 脱水对象??),但是 出于某种原因,我得到 0 次命中,更令人担忧的是 0 次未命中,所以看起来它在查找时根本不会进入缓存,即使统计代码似乎告诉我内存中有 10000 个对象。

对我在做什么有什么想法吗?我认为我得到未命中的事实是好的,因为这意味着正在使用缓存,但我无法弄清楚为什么我没有得到任何缓存命中。是不是因为我使用了 setFirstResult()setFetchSize() 标准。

System.out.println("Cache Misses = " + stats.getSecondLevelCacheMissCount());
System.out.println("Cache Hits Count = " + stats.getSecondLevelCacheHitCount());

System.out.println("2nd level elements in mem "+ stats.getSecondLevelCacheStatistics("com.SomeTestEntity").getElementCountInMemory());

最佳答案

二级缓存用于“按主键查找”。对于其他查询,您需要缓存查询(假设启用了查询缓存),在您的情况下使用 Criteria#setCacheable(boolean) :

Criteria crit = HibernateUtil.getSession().createCriteria( persistentClass );
crit.setFirstResult(startIndex);
crit.setFetchSize(fetchSize);
crit.setCachable(true); // Enable caching of this query result
return crit.list();

我建议阅读:


If I cache the query, are all them hibernate entities from the query then available in the second level cache?

是的,他们会的。这在我提到的链接中以白底白字解释:“请注意,查询缓存不缓存结果集中实际实体的状态;它只缓存标识符值和值类型的结果。所以查询缓存应始终与二级缓存结合使用”。你读了吗?

As i was under the impression that using the query cache was entirely different than using the hibernate 2nd level cache.

它是不同的(用于缓存条目的“键”是不同的)。但是查询缓存依赖于二级缓存。

From your answer you seem to be suggesting that the query cache and second level cache are both the same, and to generate cache hits I need to be using the "find by primary key".

我只是说您需要缓存查询,因为您不是“通过主键查找”。我不明白什么是不清楚的。您是否尝试在查询或条件对象上调用 setCacheable(true)?很抱歉坚持,但是你读过我发布的链接了吗?

关于java - Hibernate 二级缓存似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3142528/

相关文章:

java - spring 和 MessagesSource 空指针异常

mysql - sequelize 你正在使用 sql 安全更新错误

Django 模型方法与自定义管理器

java - 模拟类将 null 分配给 @NonNull 字段(Android)

java - 简单ArrayList程序-JAVA

c# - 我应该在具有固定类型大小的语言(如 Java、C#)中的 64 位上使用 'long' 而不是 'int'

java - 使用 spring-boot-starter-data-jpa 时出现 Hibernate-core 错误

java - 如何对具有多个地址的用户进行建模?

java - Android 音乐播放器无法从 onCreate 自动启动

orm - Gorm Golang orm 关联