您的位置:首页 > 其它

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

2015-02-08 14:26 435 查看
一:知识点

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对象最大生存时间,一般大于timeToIdleSeconds

overflowToDisk 内存溢出的时候,存放到硬盘上 <diskStore path="java.io.tmpdir"/>

-->



<defaultCache

maxElementsInMemory="10000"

eternal="false"

timeToIdleSeconds="120"

timeToLiveSeconds="120"

overflowToDisk="true"

/>



(4):在需要二级缓存的对象前面加上Annotation

@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)

@Entity

public 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


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: