MyBatis框架的缓存
正如大多数持久层框架一样,MyBatis 同样提供了一级缓存和二级缓存的支持 一级缓存: 基于PerpetualCache 的 HashMap本地缓存,其存储作用域为 Session,当 Session flush 或 close 之后,该Session中的所有 Cache 就将清空。
MyBatis框架的缓存分类:
一级缓存:
MyBatis框架的一级缓存是基于PerpetualCache的HashMap本地缓存,默认是SqlSession级别的缓存,在SqlSession的一个生命周期内有效。当SqlSession关闭后,该SqlSession中的一级缓存会被清空。MyBastis框架的一级缓存默认是开启的。
二级缓存:
****二级缓存是SqlSessionFactory级别的,其作用域超出一个SqlSession的范围,缓存中的数据可以被所有SqlSession共享。MyBatis框架的二级缓存默认是关闭的,使用时需要在MyBatis框架的核心配置文件中设置开启。
二级缓存的使用方法:
1 导入第三方ehcache包
2 在hibernate.cfg.xml添加
<property name="hibernate.cache.provider_class">
org.hibernate.cache.EhCacheProvider
</property>
3 在对应的 pojo类中添加 缓存标签
<cache usage="read-write"/>
<cache usage="read-write"/>
4 ehcache.xml放在 src目录下 这个文件在hibernate官方下载包里的下面就有
<ehcache>
<diskStore path="c://ehcache/"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
<!-- 设置Category类的缓存的数据过期策略 -->
<cache name="org.qiujy.domain.cachedemo.Category"
maxElementsInMemory="100"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/>
<!-- 设置Category类的products集合的缓存的数据过期策略 -->
<cache name="org.qiujy.domain.cachedemo.Category.products"
maxElementsInMemory="500"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
<cache name="org.qiujy.domain.cachedemo.Product"
maxElementsInMemory="500"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
</ehcache>
| 参数名 | 说明 |
| type | 指定缓存(cache)接口的实现类型,当需要和ehcache整合时更改该参数值即可。 |
| flushInterval | 刷新间隔。可被设置为任意的正整数,单位毫秒。默认不设置。 |
| size | 引用数目。可被设置为任意正整数,缓存的对象数目等于运行环境的可用内存资源数目。默认是1024。 |
| readOnly | 只读,true或false。只读的缓存会给所有的调用者返回缓存对象的相同实例。默认是false。 |
| eviction | 缓存收回策略。LRU(最近最少使用的),FIFO(先进先出),SOFT( 软引用),WEAK( 弱引用)。默认是 LRU。 |
提示:
****对于MyBatis框架的缓存仅做简单了解即可,因为数据量达到一定规模,内置的缓存机制将无法满足要求。MyBatis框架的核心是SQL管理,缓存数量并不是MyBatis框架所擅长的,所有采用Redis、MongoDB、OSCache、Memcached等专业的缓存服务器会更加合理。