缓存的作用主要用来提高性能,可以简单的理解成一个Map;使用缓存涉及到三个操作:把数据放入缓存、从缓存中获取数据、删除缓存中的无效数据。
一、hibrnate内部缓存分析:
1、一级缓存:Session级别的缓存
特点:生命周期短、作用范围小。随着session的结束而结束!
缺陷:没有任何的保护,不能存过多数据,否则缓存会溢出!共享范围太小。
什么时候将数据放入缓存?
答:save,update,saveOrUpdate,load,get,list,iterate,lock这些方法都会将对象放在一级缓存中
什么时候从缓存中提取数据?
答:查询的时候:get()、load()先去缓存中找,如果有直接返回;如果没有则从数据库中找。Criteria、query接口实现的查询,不从缓存中提取数据
注:一级缓存不能控制缓存的数量,所以要注意大批量操作数据时可能造成内存溢出;可以用evict(清除一级缓存中的一个对象),clear(清除一级缓存中的所有对象)方法清除缓存中的内容。
2、二级缓存:sessionFactory级别缓存
·实现为可插拔,通过修改cache.provider_class参数来改变;
hibernate内置了对EhCache,OSCache,TreeCache,SwarmCache的支持,可以通过实现CacheProvider和Cache接口来加入Hibernate不支持的缓存实现。
·在hibernate.cfg.xml中加入:
<class-cache class="className" usage="read-only"/>
或在映射文件的class元素加入子元素:
<cache usage="read-write"/>
其中usage:read-only,read-write,nonstrict-read-write,transactional。
在配置文件中配置二级缓存,主要高速hibrnae第三方缓存的提供者是谁。
(1) cache.use_second_level_cache:true决定要不要打开二级缓存打开,这个属性的默认值就是true
(2)cache.provider_class:cache的提供者是谁
<property name="cache.provider_class">
org.hibernate.cache.OSCacheProvider
</property>
(3)需要将oscache相关的jar包构建到项目中
(4)需要将oscache.properties拷贝src目录下
(5)方法一:在配置文件中<class-cache class=”com.hbsi.domain.User” usage=””>:告诉hibrnate哪些类是需要放入缓存的:
Usage: reade-only 效率高,但是有一个限制数据库不能被修改、Read-writer、nonstruct-read-writer、transactional
方法二:在映射文件中<cache usage="read-write"/>告诉hibernate
命中:
错过:
<property name=”gengerate_statisyics”>true</property>
对调是有很大的帮助,产生统计信息
在statistics st=session.getStatistics();//得到缓存统计信息
Statistics[
Start time=1324006095531,
sessions opened=0,
sessions closed=0,
transactions=0,
successful transactions=0,
optimistic lock failures=0,
flushes=0,
connections obtained=0,
statements prepared=0,
statements closed=0,
second level cache puts=0,
second level cache hits=0,
second level cache misses=0,
entities loaded=0,
entities updated=0,
entities inserted=0,
entities deleted=0,
entities fetched=0,
collections loaded=0,
collections updated=0,
collections removed=0,
collections recreated=0,
collections fetched=0,
queries executed to database=0,
query cache puts=0,
query cache hits=0,
query cache misses=0,
max query time=0
]