传智播客Hibernate视频教程学习笔记40

时间:2023-02-26 21:01:51

 Hibernate二级缓存的分析与配置:

Hibernate采用第三方缓存控制,我们使用oscache来演示首先需要加入oscache2.1.jar这个库文件,在Hibernate3.3.2中lib文件夹下的optional文件夹内。

 

另外需要加入oscache的配置文件,在Hibernate3.3.2/porject/etc下找到oscache.proprities文件,黏贴到工程src目录下即可

 

我用的是Hibernate3.3.2,还需要加载common-logging-1.1.jar这个库,因为oscache使用的日志框架是common-logging。

 

添加完以后我们修改hibernate.cfg.xml配置文件:加入

 

 <property name="cache_user_second_level_cache">true</property>

使用二级缓存
 <property name="cache.provider_class">org.hibernate.cache.OSCacheProvider</property>

使用oscache

 

另外我们还需要指定哪些类需要采用缓存机制,以Users为例

修改Users.hbm.xml配置

<cache usage="read-only" />

对Users类进行缓存,策略为read-only

策略有很多种,

read-only只读

reda-write严格读写,多线程时会做同步

nonstrict-read-write不严格的读写

transactional事务性缓存

 

 

test.java

第一次使用HibernateUtil的get方法后,session已经关闭

2009-8-7 9:54:14 com.opensymphony.oscache.base.Config loadProps
信息: Properties {cache.capacity=1000}
2009-8-7 9:54:15 com.opensymphony.oscache.base.Config loadProps
信息: Properties {cache.capacity=1000}
2009-8-7 9:54:15 com.opensymphony.oscache.general.GeneralCacheAdministrator <init>
信息: Constructed GeneralCacheAdministrator()
2009-8-7 9:54:15 com.opensymphony.oscache.general.GeneralCacheAdministrator createCache
信息: Creating new cache


Hibernate: insert into Users (name, birthday) values (?, ?)
Hibernate: select users0_.id as id0_0_, users0_.name as name0_0_, users0_.birthday as birthday0_0_ from Users users0_ where users0_.id=?

前部分是common-logging的日志,后面的sql语句可以看出,我们只做了一次数据库的访问,oscache运行成功。

 

 

下面输出一下oscache的统计信息看看,即cache的命中率,当然打开统计信息消耗不少的资源

hibernate.cfg.xml中加入

<!-- 打开二级缓存统计信息 -->
  

 

test.java中加入

 

输出:

Statistics[start time=1249610914802,sessions opened=3,sessions closed=3,transactions=1,successful transactions=1,optimistic lock failures=0,flushes=1,connections obtained=2,statements prepared=2,statements closed=2,second level cache puts=1,second level cache hits=1,second level cache misses=1,entities loaded=1,entities updated=0,entities inserted=1,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]