Hibernate学习:一级缓存和二级缓存

一:知识点

1:缓存概念与分类

缓存:在内存中开辟一块空间,把本来应该存储在数据库的数据,存储在硬盘上。

Hibernate有三种缓存:一级缓存二级缓存查询缓存

2:各种缓存的特点

(1)session级别的缓存为一级缓存,session之间不能共享缓存(2)二级缓存又叫sessionFactory级别的缓存,可以跨session(3)查询缓存:重复性查询,查询对象跟条件一致,可以从二级缓存找。如果查询不重复,不会使用二级缓存。

3:如何配置二级缓存

(1)、首先要打开二级缓存,在hibernate.cfg.xml中添加如下配置: <property name="hibernate.cache.use_second_level_cache">true</property> (2)、Hibernate的二级缓存使用第三方的缓存工具来实现,,所以我们需要指定Hibernate使用哪个 缓存工具。如下配置指定Hibernate使用EhCache缓存工具。 <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>(3):加入ehcache.xml<– maxElementsInMemory 最大缓存对象eternal = false内存可以清除timeToIdleSeconds 如果对象多长时间没有查询,将对象清除timeToLiveSeconds对象最大生存时间,一般大于timeToIdleSecondsoverflowToDisk 内存溢出的时候,存放到硬盘上 <diskStore path="java.io.tmpdir"/> –> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" /> (4):在需要二级缓存的对象前面加上Annotation @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)@Entitypublic class User {执行查询,报错 Exception in thread "main" org.hibernate.HibernateException:could not instantiate RegionFactory [org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge] (5):需要加入Ecache的jar包ehcache-1.2.3.jar 执行查询Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory(6):需要加入commons-logging-1.1.jar二:缓存demo

出门走好路,出口说好话,出手做好事。

Hibernate学习:一级缓存和二级缓存

相关文章:

你感兴趣的文章:

标签云: