mybatis缓存的使用及理解

时间:2021-11-08 05:13:58



和hibernate一样,mybatis也有缓存机制 
一级缓存是基于 PerpetualCache(mybatis自带)的 HashMap 本地缓存,作用范围为session,所以当session commit或close后,缓存就会被清空 

二级缓存默认也是基于 PerpetualCache,但是可以为其制定存储源,比如ehcache 

一级缓存缓存的是SQL语句,而二级缓存缓存的是结果对象,看如下例子(mybatis的日志级别设为debug)

?
12345678 List<User>
users = sqlSession.selectList(
"com.my.mapper.UserMapper.getUser","jack");
System.out.println(users);  //sqlSession.commit();①   List<User>
users2 = sqlSession.selectList(
"com.my.mapper.UserMapper.getUser","jack");//②admin
System.out.println(users);

结果是只发起一次SQL语句,如果我们把②出的参数jack改为admin,发现还是只发起一次SQL语句,但是会设置不同参数

如果把①处去掉注释,会发现不会有缓存了


下面就来启用二级缓存

在配置文件中启用二级缓存

?
1 <setting
name
="cacheEnabled"
value
="true"
/>
在需要进行缓存的mapper文件UserMapper.xml中加上 ?
1 <cache
readOnly
="true"></cache>
注意这里的readOnly设为true,默认是false,表示结果集对象需要被序列化


我们打开①处注释,②处仍然使用jack,我们发现结果只执行了一次SQL语句

但是如果把②处改为admin,执行了2次SQL语句,这说明二级缓存是缓存结果集对象的


下面我们来使用ehcache

在classpath下添加ehcache.xml

在UserMapper.xml中添加:

?
12 <!--
<cache readOnly="true" type="org.mybatis.caches.ehcache.LoggingEhcache"/>   -->
<cache
type
="org.mybatis.caches.ehcache.EhcacheCache"/>
用上面那个会输出更加详细的日志,下面的不会

需要用到ehcache.jar,下载地址:http://sourceforge.net/projects/ehcache/files/ehcache/ehcache-2.7.0/ehcache-2.7.0-distribution.tar.gz/download

mybatis-ehcache.jar下载地址:http://code.google.com/p/mybatis/downloads/detail?name=mybatis-ehcache-1.0.2-SNAPSHOT-bundle.zip&can=3&q=Product%3DCache