二级缓存的开启

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、Hibernate在默认情况下并不会对所有实体对象进行缓存,所以,我们需要指定缓存哪些对象,  
在实体对象的映射文件中(相应的<class>标签内部),添加如下配置:  
<cache usage="read-only"/> 
 
usage="read-only"是“只读”缓存策略。  
 
注意,这个<cache>标签只能放在<class>标签的内部,而且必须处在<id>标签的前面!!!  
这个<cache>标签放在哪些<class>标签下面,就说明会多这些类的对象进行缓存  
 
4、对于第3步,有一个可选的方案是在hibernate.cfg.xml文件中指定哪些类的对象需要缓存,  
   而不需要使用<cache>标签来指定。如:  
   在hibernate.cfg.xml中添加如下配置:  
   <class-cache class="com.bjsxt.hibernate.Classes" usage="read-only" /> 
    
  注意,这个<class-cache>标签必须放在<mapping>标签的后面!!  


=================================================
一级缓存也叫Session级缓存,hibernate在执行save,update,saveOrupdate,get,load,list,iterate,lock方法时,会将数据放入一级缓存中,一级缓存中的数据可以通过evict和clear方法清理,它也会随着session的生命的结束而结束,也就是说当session生命周期结束或者session被关闭时,一级缓存中的数据随之清除。
二级缓存也叫sessionFactory缓存,二级缓存需要配置,二级缓存交给了第三方进行处理,常见的二级缓存支持有EHCache,OSCache,Hashtable,由于一级缓存有限(内存有限,session生命周期有限),所以二级缓存是一级缓存的弥补,二级缓存的生命跟SessionFactory有关联,二级缓存在sessionFactory生命周期中存在,二级缓存可以在内存和磁盘中。
hibernate查询数据,先从一级缓存中找,如果一级缓存中存在,则返回数据,一级缓存中不存在,就从数据库中找,在数据库中找到后,将数据放入一级缓存,如果配置了二级缓存,则是先从一级缓存中找,如果一级缓存不存在,再从二级缓存中找,如果二级缓存存在,则返回数据,如果二级缓存中不存在,则从数据库中找,在数据库中找到后,将数据放入一级缓存和二级缓存。
二级缓存有一个统计数据命中率的方法,数据命中率越高越好。
二级缓存的OSCache.property文件配置capacity大小和缓存在内存还是磁盘。
hibernate_cache_second_level true
cache_privider_class org.hibernate.cache.OSCachePrivider
hibernate_generate_statictis true
mapping Student.hbm.xml
class-cache class Student usage read-only,read-write,nonstrict-read-write,transactional
OSCache.jar,log4j.jar,OSCache.propertiry

<hibernate-configuration> <session-factory> <!-- 开启二级缓存 --> <property name="hibernate.cache.use_second_level_cache">true</property> <!-- 设置缓存提供者 --> <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> <mapping resource="cn/ineeke/entity/User.hbm.xml"/> <!-- 指定哪些实体需要使用二级缓存 --> <class-cache class="cn.ineeke.entity.User" usage="read-only"/> </session-factory> </hibernate-configuration>


猜你喜欢

转载自yuhuiblog6338999322098842.iteye.com/blog/2186208