hibernate的二级缓存

来源:互联网 发布:义乌市盛灿网络 编辑:程序博客网 时间:2024/05/16 18:24

1.把hibernate中相应的缓存架包导入项目中,一般用OSCache

2.将oscache的oscache.properties放入。在该文件中可以修改oscache的缓存大小,默认的是1000:

      cache.capacity=1000

3.在sessionFactory中写入相应的二级缓存,用到二级缓存的类及缓存策略

      <propertyname=”cache.provider_class”>

          org.hibernate.cache.OSCacheProvider

      </property>

      <class-cacheclass = “cn.itcast..dao.entity.User” usage=”read-only”/>

      如果该类以后不需要修改则用readonly,修改则用read-write

3(+).若不用步骤3在hibernate.cfg.xml中指定缓存可以在实体类的相应配置文件中指定,如在User.hbm.xml中,在id属性的上一行指定:

       。。。。。。

       <cache usage=”readonly”>

       <id name=”id”><generator class=”native”/></id>

       。。。。。。

4.在sessionFactory中启动缓存查询命令

              <propertyname=”cache.use_query_cache”>true</property>

5.get,load和iterator方法可以按以上配置直接从缓存中读取数据

6.query与criteria由于查询命中率低,所以对他们默认的查询缓存是不支持的。

       它们必须在hibernate.cfg.xml中设置查询对象是支持缓存的。

       比如query查询要设置Query的对象query支持缓存:query.setCacheable(true)

       缓存命中率:比如查询100次数据,有几次数据是从缓存中找到的。

 

 

一级缓存可以用evict或clear方法清掉(eict是清理一条缓存,clear是清理全部)

二级缓存可以用evict方法清理